java - LazyInitializationException 尽管有 Spring 事务?

标签 java hibernate spring jpa

下面的方法导致 org.hibernate.LazyInitializationException 被抛出,我很感激帮助理解原因。我正在使用 JPA 2/Hibernate & Spring。

JPA 2/Hibernate 使用默认的 transaction 持久化上下文,因此,下面的方法不应该允许延迟加载吗?

@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>

最佳答案

我们需要更多的信息来诊断它,但我倾向于看到您的签名是它位于未被代理的 Controller 类中。 @Transactional 仅适用于由 bean 工厂代理的类,以许多常见的方式设置上下文,这不包括 Controller 类。

关于java - LazyInitializationException 尽管有 Spring 事务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4687750/

相关文章:

java - 如何在 EJB 中找到服务器的 IP 地址

java - 如何在 Java selenium 的 POM-TestNG 类中使用 SELECT 语句

java - Hibernate:遍历数百万行并且不泄漏内存

spring - 如何在基于 Spring 的强类型语言中正确执行 PATCH - 示例

java - 使用注释将默认值注入(inject) Spring bean

javascript - 从 Spring MVC Controller 中检索 ModelMap 值到 html 中的 jquery

java - 如何将 Spring 计划任务配置为在具有特定延迟的时间范围内运行?

java - PDF 生成的高级接口(interface)

hibernate - 使用 Hibernate 进行国际化

hibernate - 按多对多关系查询时从结果列表中排除项目