Get org.hibernate.LazyInitializationException in spring boot integration test

I am trying to write an integration test for a Spring Boot application. I have a product model and GalleryImage. They are connected to each other.

public class Product {
    ...

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

I have an integration test as shown below:

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

However, this test gives me a LazyInitializationException. I searched on Google and StackOverFlow, it says that the session is closed after productRepository.findOne (1L), since galleryImages are lazily loading, so galleryImages.size () gives me this exception.

I tried adding the @Transactional annotation in the test, but it still does not work.

+4
source share
1 answer

Hibernate productRepository.findOne(1L).

Hibernate.initialize(product.getGalleryImages())

public static void initialize(Object proxy)
                   throws HibernateException

. . - ; , INSIDE /.

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 , - .

0

All Articles