在Hibernate中,session建立时如getCurrentSession();不会获取数据库的链接,只有在beginTransaction()时才会从链接池里得到链接,默认情况下当事务commit或者rollback时session会flush,随后链接会被释放,新的事务会得到新的链接。
在使用spring整合hibernate时,一般采用代理模式来管理 事务,所以在 dao里,不需要我们手动的去获取 transaction和 commit事务。例如下面的代码所示。
以前我一直有疑问,因为在dao里执行完某个查询操作后,session就会被关闭。这样得到的就是个detached对象,很多情况下就应该有LazyInitializationException。我一直都不明白开发架构是如何解决这个问题的。
《java persistence with hibernate》的16章有相关的描述,一种解决方法是Open Session in View (OSIV),这种比较好理解,就是利用filter扩展整个session,"leave the persistence context open until the view is completely rendered."。它适用于“the presentation,business,and persistence layers are colocated on the same virtual machine.” 我们所要做的就是在web.xml加上
如果是分布式系统里OSIV就不行了,只得用其他的解决方法,如session facade, DTO(data transfer object) and command。
在使用spring整合hibernate时,一般采用代理模式来管理 事务,所以在 dao里,不需要我们手动的去获取 transaction和 commit事务。例如下面的代码所示。
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" /> </property>
</bean>
<bean id="transactionInterceptor"
class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager">
<ref bean="txManager" />
</property>
<property name="transactionAttributes">
<props>
<prop key="search*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="save*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
<!-- BeanNameAutoProxyCreator -->
<bean id="autoProxyCreator"
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="interceptorNames">
<list>
<value>logInterceptor</value>
<value>transactionInterceptor</value>
</list>
</property>
<!-- Add all the services to here for transaction and rollback -->
<property name="beanNames">
<list>
<!-- put in service interfaces here for transaction management -->
<idref bean="registrationService" />
</list>
</property>
</bean>
以前我一直有疑问,因为在dao里执行完某个查询操作后,session就会被关闭。这样得到的就是个detached对象,很多情况下就应该有LazyInitializationException。我一直都不明白开发架构是如何解决这个问题的。
《java persistence with hibernate》的16章有相关的描述,一种解决方法是Open Session in View (OSIV),这种比较好理解,就是利用filter扩展整个session,"leave the persistence context open until the view is completely rendered."。它适用于“the presentation,business,and persistence layers are colocated on the same virtual machine.” 我们所要做的就是在web.xml加上
<filter>
<filter-name>sessionFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>sessionFilter</filter-name>
<url-pattern>*.faces</url-pattern>
</filter-mapping>
如果是分布式系统里OSIV就不行了,只得用其他的解决方法,如session facade, DTO(data transfer object) and command。