Search code examples
javaspring-boothibernatejpalazy-loading

String + Jpa + Hibernate, force collection eager initialization on only specific method without transaction


Very simple question and i would like a simple answer.
I'm loading one entity with many lazy collection associated. This load is done outside a @Transactional method for personal reasons

right after loading the entity i try loading the collections but i get exception

final A cachedEntity = aRepository.find(entity.getDocument());
         final Session session = sessionFactory.openSession();
         session.beginTransaction();
         Hibernate.initialize(cachedEntity.getAddresses()); // exception right here
         cachedEntity.getAddresses().addAll(entity.getAddresses());
         cachedEntity.getPhones().addAll(entity.getPhones());
         cachedEntity.getEmails().addAll(entity.getEmails());
         session.close();


failed to lazily initialize a collection of role:  addresses, could not initialize proxy - no Session

This is supposed to be super simple, what am i doing wrong?
please dont suggest annotate collections with eager or add @transactional to method


Solution

  • The solution is very simple, I'll share to help others.
    I knew there should be a way to tell jpa to force eager load a collection for one specific query only, and there is.

    In the repository interface annotate the specific query you want to have eager load with

    @EntityGraph(attributePaths = {"lazyCollectionA", "lazyCollectionB"}, type = EntityGraph.EntityGraphType.LOAD)
       A find(/*PARAMETERS_HERE*/);
    

    this way when spring builds this query it will create a inner join for the specified collections and eager initialize them.

    Another approach would be specify the whole query in the @Query annotation specifing the inner joins you want. but as i want take advantage of spring auto generated queries i just use the @EntityGraph