hibernate—懒加载问题解决
2017-07-08 00:00
211 查看
错误:
这上面的大概意思为:不能加载集- 这里是列表文本合,cn.bos.domain.base包下的Courier.fixedAreas属性,不能初始化代理。
原因:我在Courier对象中关联了下面的集合属性
在做json懒加载的时候,不会去加载这个集合。因为实体的集合属性默认会被延迟加载,实体所关联的实体默认也会被延迟加载。
遇到这种异常的时候先要分析:到底要不要去加载这个集合对象
因为我返回的json对象是不需要这个集合对象,因此可以用@Json注解来排除不需要加载的属性
只需要在相应的get方法的上面加上@JSON(serialize=false)就能解决本次遇到的问题。
这里有篇详细的文章讲解了
Hibernate 延迟加载剖析与代理模式应用
如果需要集合属性,解决方法如下
在web.xml文件中配置:
说明:上面的配置表示session不会提前关闭。
Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: cn.bos.domain.base.Courier.fixedAreas, could not initialize proxy - no Session
这上面的大概意思为:不能加载集- 这里是列表文本合,cn.bos.domain.base包下的Courier.fixedAreas属性,不能初始化代理。
原因:我在Courier对象中关联了下面的集合属性
@ManyToMany(mappedBy = "couriers") private Set<FixedArea> fixedAreas = new HashSet<FixedArea>();
在做json懒加载的时候,不会去加载这个集合。因为实体的集合属性默认会被延迟加载,实体所关联的实体默认也会被延迟加载。
遇到这种异常的时候先要分析:到底要不要去加载这个集合对象
因为我返回的json对象是不需要这个集合对象,因此可以用@Json注解来排除不需要加载的属性
只需要在相应的get方法的上面加上@JSON(serialize=false)就能解决本次遇到的问题。
@JSON(serialize=false) public Set<FixedArea> getFixedAreas() { return fixedAreas; }
这里有篇详细的文章讲解了
Hibernate 延迟加载剖析与代理模式应用
如果需要集合属性,解决方法如下
在web.xml文件中配置:
<filter> <filter-name>Spring OpenEntityManagerInViewFilter</filter-name> <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class> <init-param> <!-- 指定org.springframework.orm.jpa.LocalEntityManagerFactoryBean在spring配置文件中的名称,默认值为entityManagerFactory 如果LocalEntityManagerFactoryBean在spring中的名称不是entityManagerFactory,该参数一定要指定,否则会出现找不到entityManagerFactory的例外 --> <param-name>entityManagerFactoryBeanName</param-name> <param-value>entityManagerFactory</param-value> </init-param> </filter> <filter-mapping> <filter-name>Spring OpenEntityManagerInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
说明:上面的配置表示session不会提前关闭。
相关文章推荐
- Spring+Hibernate+Struts之懒加载问题的解决
- failed to lazily initialize a collection of role: no session or session was closed (Hibernate) 解决方法(延迟加载问题)
- Spring使用OpenSessionInViewFilter解决Hibernate的lazy延时加载问题
- Spring+Hibernate+Struts之懒加载问题的解决
- 解决org.hibernate.LazyInitializationException: could not initialize proxy - no Session懒加载问题
- Hibernate延时加载lazy机制问题及其解决方法
- Spring中解决Hibernate的lazy加载问题
- Json lib 对于hibernate的懒加载的存在问题的解决方法
- json解决hibernate中级联对象延迟加载有关问题
- hibernate+spring mvc, 解决hibernate 对象懒加载 json序列化问题
- Hibernate延迟加载 或 no session or session was closed 问题的解决(OpenSessionInViewFilter使用)
- hibernate懒加载导致对象json化失败问题解决
- Hibernate延迟加载以及利用Spring事务完美解决延迟加载问题
- Spring+Hibernate+Struts之懒加载问题的解决
- DWR3.0解决hibernate延迟加载问题
- Hibernate延时加载lazy机制问题及其解决方法
- Spring中解决Hibernate的lazy加载问题
- 解决Hiberante延迟加载问题——could not initialize proxy - no Session & 简介Hibernate的持久化
- 彻底解决SSH架构中的Hibernate懒加载问题
- Spring使用OpenSessionInViewFilter解决Hibernate的lazy延时加载问题