尽管是Spring事务,LazyInitializationException?

时间:2011-01-14 03:37:25

标签: java hibernate spring jpa

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

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>

3 个答案:

答案 0 :(得分:3)

我们需要更多的信息来诊断这些信息,但是我看到你签名的倾向是它在一个没有被代理的控制器类中。 @Transactional只能用于bean工厂代理的类,在很多常见的方法中设置上下文,这不包括控制器类。

答案 1 :(得分:0)

@Affe要求的是你的弹簧配置?如果您收到LazyInitializationException,则没有适当的事务。正如@Affe所提到的,只有在创建代理时才会启动Transaction,这可能是因为您的配置中存在某些问题。

答案 2 :(得分:0)

我在调用

时遇到了同样的问题
session.clear();

介于两者之间

entity = session.get(...);

entity.getLazyCollection();

因此,只需检查您的代码,不要使用此方法。

相关问题