Hibernate session,transaction

在Hibernate中,session建立时如getCurrentSession();不会获取数据库的链接,只有在beginTransaction()时才会从链接池里得到链接,默认情况下当事务commit或者rollback时session会flush,随后链接会被释放,新的事务会得到新的链接。

在使用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。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值