Reputation: 10571
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?
Upvotes: 4
Views: 4727
Reputation: 3180
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();
}
Upvotes: 1
Reputation: 753
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
Upvotes: 7