4

If I have an Entity Person with some lazy-collections (Cars, Bills, Friends, ...) and want to write a JpaRepository-method that gives me all persons indluding eagerly fetched Cars, is this possible?

I know that one can do this on single objects, but is this somehow possible with collections of persons?

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
codepleb
  • 10,086
  • 14
  • 69
  • 111
  • Possible duplicate of [Hibernate Spring JPA load only specific lazy relationship](https://stackoverflow.com/questions/40932584/hibernate-spring-jpa-load-only-specific-lazy-relationship) – crizzis Jun 22 '17 at 12:43

2 Answers2

7

Yes, there is a very convenient @EntityGraph annotation provided by Spring Data JPA. It can be used to fine tune the used entitygraph of the query. Every JPA query uses an implicit entitygraph, that specifies, which elements are eagerly or lazy fetched depending on the relations fetchtype settings. If you want a specific relation to be eagerly fetched you need to specify it in the entitygraph.

@Repository
public interface PersonRepository extends CrudRepository<Person, Long> {
   @EntityGraph(attributePaths = { "cars" })
   Person getByName(String name);
}

Spring Data JPA documentation on entity graphs

Florian Schmitt
  • 753
  • 3
  • 8
1

Use the following JPA query to get the both tables data. Here used jpa query to fetch the cars.

A "fetch" join allows associations or collections of values to be initialized along with their parent objects using a single select. This is particularly useful in the case of a collection. It effectively overrides the outer join and lazy declarations of the mapping file for associations and collections.

See this for more explanation on join fetch

Use the "join fetch", to fetch object eagerly.

public interface CustomRepository extends JpaRepository<Person, Long> {

    @Query("select person from PersonModel as person left join fetch person.cars as cars")
    public PersonModel getPersons();
}
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
Sudhakar
  • 3,104
  • 2
  • 27
  • 36