spring4+springmvc+springdataJPA+hibernate4+Junit4整合懒加载问题

文章目录

      • 技术交流

#摘要
本文主要是为了解决“spring4+springmvc+springdataJPA+hibernate4+junit4整合”,注解了OneToMany、ManyToOne,并配置了懒加载,然后报错的问题

##第一个问题

org.hibernate.LazyInitializationException: could not initialize proxy - no Session at

###解决办法:
在web.xml中,配置springSevlet的位置,使用org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter,代码如下:

<filter>
        <filter-name>Spring OpenEntityManagerInViewFilterfilter-name>
        <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>Spring OpenEntityManagerInViewFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

##第二个问题

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: ......., no session or session was closed

一般是在定时任务quartzJob中,或者Junit测试中使用懒加载出现的错误

###解决办法:
添加事务配置注解。junit代码如下:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
		"file:src/main/webapp/WEB-INF/applicationContext.xml",
		"file:src/main/webapp/WEB-INF/demo-servlet.xml"})
@Transactional
public class Test {

完毕。

— --- — ---> 点击查看更多最新原创博文<— --- — ---

技术交流

spring4+springmvc+springdataJPA+hibernate4+Junit4整合懒加载问题_第1张图片

你可能感兴趣的:(经验集锦,天坑集锦)