下面的方法导致抛出org.hibernate.LazyInitializationException,感谢您对理解原因的帮助.我正在使用JPA 2 /休眠&弹簧.
JPA 2 / Hibernate使用默认的事务持久性上下文,因此,下面的方法是否不应该允许延迟加载?
@Service
public class GalleryService {
@Transactional(readOnly=true)
public Response getGallery(@PathParam("id") int id) {
Gallery g = daoWrapper.findById(Gallery.class,id);
...
GalleryDto gDto = new GalleryDto();
...
// getImages() returns a collection of 'image' objects.
gDto.setImages(g.getImages());
return Response.ok(gDto).build();
}
}
注意:daoWrapper是包装实体管理器方法的便捷类.
@Repository
public class daoWrapper implements BaseDao {
@PersistenceContext(unitName="persistStore")
private EntityManager em;
@Override
public <T,U> T findById(Class<T> entity,U id) {
return this.em.find(entity,id);
}
...
}
应用程序上下文文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:property-placeholder location="classpath:database.properties" />
<context:annotation-config />
<context:component-scan base-package="com.myapp.services"/>
<tx:annotation-driven/>
...
</beans>
最佳答案
我们需要诊断的信息还很多,但是我倾向于看到您的签名是,它不在控制器类中. @Transactional仅在bean工厂代理的类上起作用,以许多常见的方式来设置上下文,这不包括控制器类.
原文链接:https://www.f2er.com/spring/531690.html