繁体   English   中英

在Spring启动集成测试中获取org.hibernate.LazyInitializationException

[英]Get org.hibernate.LazyInitializationException in spring boot integration test

我正在尝试为Spring Boot应用程序编写集成测试。 我有Product和GalleryImage域模型。 他们是一对多的关系。

public class Product {
    ...

    @OneToMany(mappedBy = "product")
    private List<GalleryImage> galleryImages;
}

我有一个集成测试如下:

@Test
public void testProductAndGalleryImageRelationShip() throws Exception {
    Product product = productRepository.findOne(1L);
    List<GalleryImage> galleryImages = product.getGalleryImages();
    assertEquals(1, galleryImages.size());
}

但是,这个测试给了我一个LazyInitializationException。 我在Google和StackOverFlow上搜索,它表示会话在productRepository.findOne(1L)之后关闭,因为galleryImages被延迟加载,所以galleryImages.size()给了我这个例外。

我试图在测试中添加@Transactional注释,但它仍然无法正常工作。

Hibernate Session已在以下行productRepository.findOne(1L)之后关闭。

你可以尝试做Hibernate.initialize(product.getGalleryImages())

 public static void initialize(Object proxy) throws HibernateException 

强制初始化代理或持久集合。 注意:这只能确保代理对象或集合的初始化; 不保证集合中的元素将被初始化/具体化。

要避免使用Hibernate.initialize您可以创建服务。

@Service
@Transactional
public class ProductService {

    @Transactional(readOnly = true)
    public List<GalleryImage> getImages(final long producId) throws Exception {
      Product product = productRepository.findOne(producId);
      return product.getGalleryImages();
  }
}

如果您在应用程序中使用Spring Data JPA ,那么动态查找器是一个不错的选择。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM