gpt4 book ai didi

java - spring boot 集成测试中获取 org.hibernate.LazyInitializationException

转载 作者:搜寻专家 更新时间:2023-11-01 03:34:19 25 4
gpt4 key购买 nike

我正在尝试为 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 上搜索,它说 session 在 productRepository.findOne(1L) 之后关闭,因为 galleryImages 是延迟加载的,所以 galleryImages.size() 给了我这个异常。

我已经尝试在测试中添加@Transactional 注释,但它仍然不起作用。

最佳答案

Hibernate Session 在 productRepository.findOne(1L) 行后关闭。

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

public static void initialize(Object proxy)
throws HibernateException

Force initialization of a proxy or persistent collection. Note: This only ensures intialization of a proxy object or collection; it is not guaranteed that the elements INSIDE the collection will be initialized/materialized.

要避免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,那么动态查找器是一个不错的选择。

关于java - spring boot 集成测试中获取 org.hibernate.LazyInitializationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36063434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com