Change FetchType.LAZY to FetchType.EAGER temporary at runtime (Hibernate/JPA)
Spring JpaRepository
allows marking queries (including custom) with org.springframework.data.jpa.repository.EntityGraph
:
@Entity Book {
@Id Long id;
@OneToMany List<Author> authors;
}
@EntityGraph(attributePaths = {"authors", "author.address"})
@Query("select b from Book b" +
" where b.id in (:ids)")
List<Book> loadAll(@Param("ids") List<Long> ids);
Hibernate has a feature called Fetch Profiles that solves this problem. It requires access to Hibernate Session
, but you can use unwrap()
to access it from EntityManager
.
If you want a pure JPA solution, you can use queries with join fetch
when loading objects in use cases that require eager fetching.
UPDATE: JPA 2.1 (implemented by Hibernate 4.3) supports a feature similar to fetch profiles - entity graphs.