Spring下Hibernate lazy load的事务解决办法

来源:互联网 发布:cn域名审核 编辑:程序博客网 时间:2024/06/07 00:48

用事务方法解决在Spring下Hibernate的延迟加载,记录一下,免得忘记。

1、applicationContext.xml里

加入以下黑体部分:

...

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:p="http://www.springframework.org/schema/p"

xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="http://www.springframework.org/schema/beans 

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

...

<bean id="transactionManager"

class="org.springframework.orm.hibernate3.HibernateTransactionManager">

<property name="sessionFactory" ref="sessionFactory" />

</bean>

<tx:annotation-driven transaction-manager="transactionManager" />

...

 

2、对进行lazy bean操作的方法添加Annotation:

@Transactional(propagation = Propagation.REQUIRED, readOnly = true)

这样这个方法范围里面对bean的操作就不会报org.hibernate.LazyInitializationException错误了

 

3、如果此bean要传出这个方法的范围,需要在方法里强制加载lazy属性:

Hibernate.initialize(bean.lazyProperty)

原创粉丝点击