Spring对JDBC提供支持----对Hibernate集成支持

来源:互联网 发布:linux lb 集群 编辑:程序博客网 时间:2024/05/20 04:31
 
1).HibernateTemplate和 HibernateDaoSupport
HibernateTemplate充分利用了Spring IoC特性,从而实现对Hibernate资源的依赖注入.
它能够保证正确地打开和关闭Hibernate Session,并自动参与到事物中.而且是线程安全的并且可重用.
2).HibernateInteceptor拦截器.
操作方式是:直接将Hibernate API 代码嵌入在try/catch块中,并且在Spring配置文件中配置好拦截器.
   <bean id = "hibernateInterceptor"
         class="org.springframework.orm.hibernate.HibernateInterceptor">
         <property name="sessionFactory">
              <ref bean="sessionFactory"/>
         </property>
   </bean>
 
   public List getinterests()throws DataAccessException{
          List list = new ArrayList();
          Session session = SessionFactoryUtils.getSession(getSessionFactory(),false);
          List listinterests =null;
          try{
               listinterests = session.find("select * from Interests");
               if(interests==null){
                 throw new Example1Exception("未找到兴趣列表");
               }
          catch(HibernateException he){
                 throw SessionFactoryUtils.convertHibernateAccessException(he);
          }
HibernateInterceptor会在每次调用getInterests之前,准备好线程安全的session.
在每次调用getInterests之后,将session关闭掉.
注意:务必使用SessionFactoryUtils获得session,因为HibernateInterceptor,HibernateTemplate内部使用了SessionFactoryUtils.
但是,使用便利方面,HibernateTemplate更方便.