I am having troubles testing whether a collection is loaded in Spring DataJpaTest.
For that I have created an entity that has id and list of items as seen below. The list should be lazy-loaded (so I am assuming it should not be loaded in the test).
@Data
@Entity
@Table(name = "examples")
public class Example {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;
@OneToMany(mappedBy = "example", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<ExampleElement> collection;
}
Repository code looks like this:
@Repository
public interface ExampleRepository extends PagingAndSortingRepository<Example, Long> {
@Query("SELECT e FROM Example e")
List<Example> findAllActive();
}
In the test I am creating a new Example entity, generating the collection, saving the entity to database and after that getting entities from database and checking whether the collections are initialized. Test code looks like this:
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
public class ExampleRepositoryTest {
@Autowired
private ExampleRepository repository;
@Test
public void myTest() {
Example example = new Example();
example.setCollection(Utils.generateCollection()))
repository.save(example);
List<Example> actives = repository.findAllActive();
// tests in a loop whether the collection is initialized which should return false
}
I have tried the following:
- Injecting TestEntityManager and getting the PersistenceUnitUtil from there using
em.getEntityManager().getEntityManagerFactory().getPersistenceUnitUtil()
and calling theisLoaded(actives.get(0).getCollection())
andisLoaded(actives.get(0), "collection")
methods - both return true - Calling
Hibernate.isInitialized(actives.get(0).getCollection())
andHibernate.isPropertyInitialized(actives.get(0), "collection")
methods, which both return true as well. - Checking what the collection contains - it is a PersistentBag containing the elements. I expect it to be null instead.
What am I missing?