天天看点

继承了HibernateDaoSupport的DAO

在继承了HibernateDaoSupport的Dao中,

 this.getsession实际上是调用了父类HibernateDaoSupport中的方法获得session。使用spring管理hibernate的SessionFactory的时候,这个方法会从session池中拿出一session。这样做有可能有问题,尽管这种方式拿到的Session会自动关闭,但是他是有一定的失效策略的,而且在超session池连接数的时候,spring无法自动的关闭这些session。  不推荐使用

 this.getHibernateTemplate().getSessionFactory().getCurrentSession()从spring管理的sessionFactory中创建一个绑定线程的session。Spring会根据该线程的执行情况来自动判断是关闭session还是延迟关闭。这样做可以避免手动的管理实务,同时一个线程最多开启和关闭一次session又可以提高程序的性能。 极力推荐使用这种方法 

    this.getHibernateTemplate().getSessionFactory().OpenSession。这种方法从spring管理的sessionFactory中创建一个session,此session不是线程绑定的。当执行完一个实务的时候自动关闭session。这种方法不用手动管理实务,但是同一个线程多次的开启和关闭session,浪费系统资源和影响执行效率,正常情况下还是不要用了。

这里getCurrentSession本地事务(本地事务:jdbc)时 要在配置文件里进行如下设置

    * 如果使用的是本地事务(jdbc事务)

 <property name="hibernate.current_session_context_class">thread</property>

 * 如果使用的是全局事务(jta事务)

 <property name="hibernate.current_session_context_class">jta</property> 

 getCurrentSession () 使用当前的session

openSession()         重新建立一个新的session 

在一个应用程序中,如果DAO 层使用Spring 的hibernate 模板,通过Spring 来控制session 的生命周期,则首选getCurrentSession ()。

值得一提的是:getCurrentSession()不仅仅是配置上<property name="hibernate.current_session_context_class">thread</property>就可以使用的,还要在事务里面用(包括查询),所以一般会在XML配置文件上加入事务管理的扩展:

<tx:advice id="txAdvice" transaction-manager="transactionManager">

<tx:attributes>

<tx:method name="*" propagation="REQUIRED" read-only="false" />

</tx:attributes>

</tx:advice>

<aop:config proxy-target-class="true">

<aop:pointcut expression="execution(* com.gns.service..*(..))"

id="perform" />

<aop:advisor pointcut-ref="perform" advice-ref="txAdvice" />

</aop:config>

其中execution(* com.gns.service..*(..))是表示:方法类型, 方法返回值(*任意类型) 方法全名(包名+类名+方法名,com.gns.service..*是指在com.gns.service包下的所有类和子包中的类,)参数((..)表示任意个数,任意类型的参数)

这个aop不能直接配置入DAO类,也就是说,当我们配置切入点表达式入DAO类时,事务是不会提交的,一般情况下是配置到上一层.例:service层.