您的位置:首页 > 编程语言 > Java开发

让spring帮助你在MVC层解决JPA的缓迟加载问题

2007-12-17 10:28 621 查看
作为EJB3.0的一部分,JPA是一个好东西。其简单的配置方式及强大的默认配置支持,使其可以轻松自由的存在于轻量与重量之间,如果现在您的JavaEE项目,不管是选择轻量级构架还是重量级构架,如果持久层不选择使用JPA,而是用一些ORM框架(如Hibernate、TopLink)的专用API,那么在将来的某一天一定会为这个选择而说出至尊宝那句“假如上天再给我一个机会…”的至理名言。
下面是一个简单的Entity,是对一个CMS系统中,关于树状信息目录实体类的定义,包括了一些详细的映射的配置信息。

@Entity
<aop:config>
<aop:pointcut id="CmsManage"
expression="execution(* com.easyjf.cms.service.*.*(..))" />
<aop:advisor advice-ref="cmsManageAdvice"
pointcut-ref="CmsManage" />
<tx:advice id="cmsManageAdvice"
transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" propagation="SUPPORTS"
read-only="true" />
<tx:method name="query*" propagation="SUPPORTS"
read-only="true" />
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<bean id="cmsManageService"
class="com.easyjf.cms.service.impl.CmsManageServiceImpl">
<property name="newsDirDao" ref="newsDirDao" />
</bean>在这里,当mvc层执行到$!info.getChildren()方法的时候,将会用到缓迟加载,由于Spring的事务是配置在service层的,因此在执行service.queryDirsByConditions方法完成后就关闭了事务。因此运行程序就会出现类似下面的错误信息:

2007-03-28 00:39:35,750 ERROR [org.hibernate.LazyInitializationException] - failed to lazily initialize a collection of role: com.easyjf.cms.domain.NewsDir.children, no session or session was closed
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.easyjf.cms.domain.NewsDir.children, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350)
at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:97)
  使用其它的mvc如struts、webwork乃至spring mvc都会有这样的问题,问题的核心是在事务启动及结束上,由于我们都习惯于在service层而非mvc配置及使用事务,导致了这样的问题。解决的办法其实很简单,就是把事务的启动放到mvc层,让mvc层的controller来开启事务,而让业务层的方法加入的事务中。比如,在EasyJWeb中,可以通过如下的配置来实现实现在action中开启事务:
  在Spring配置文件中配置EasyJWeb的核心处理器,并把process方法添加到事务中,配置文件如下:

<aop:config>
<aop:pointcut id="easyjwebProcessor"
expression="execution(* com.easyjf.web.RequestProcessor.process(..))" />
<aop:advisor advice-ref="txEasyjwebProcessorAdvice"
pointcut-ref="easyjwebProcessor" />
</aop:config>
<tx:advice id="txEasyjwebProcessorAdvice"
transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" read-only="true" />
</tx:attributes>
</tx:advice>
<bean name="EasyJWeb-Processor" class="com.easyjf.web.core.DefaultRequestProcessor"/>  只需要这样简单的配置,你会惊奇的发现,所有缓迟加载及其它由Persitence Context无效而引起的问题均解决了。

关于easyjweb与spring的集成,有兴趣的朋友请参考stef_wu的《在EasyJWeb使用spring容器》一文。

Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1543463
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: