Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data JPA findAll with different EntityGraph

in Spring Data JPA Repository i need to specify multiple methods that do the same thing (eg. findAll) but specifying different @EntityGraph annotation (the goal is to have optimized methods to use in different services).

Es.

@Repository
public interface UserRepository extends JpaSpecificationExecutor<User>, JpaRepository<User, Long> {

@EntityGraph(attributePaths = { "roles" })
findAll[withRoles](Specification sp);

@EntityGraph(attributePaths = { "groups" })
findAll[withGroups](Specification sp);

etc...
}

In Java we can't have same method sign multiple times, so how to manage it?

Is it possible without using JPQL?

Thanks,

Gabriele

like image 724
Gabriele Muscas Avatar asked May 30 '26 19:05

Gabriele Muscas


1 Answers

You can use EntityGraphJpaSpecificationExecutor to pass different entitygraph based on your method.

@Repository
public interface UserRepository extends JpaSpecificationExecutor<User>, JpaRepository<User, Long>, EntityGraphJpaSpecificationExecutor<User> {

}

In your service class, you can call find all with entity graph.

List<User> users = userRepository.findAll(specification, new NamedEntityGraph(EntityGraphType.FETCH, "graphName"))

Like above, you can use a different entity graph different based on your requirement.

like image 138
SSK Avatar answered Jun 01 '26 09:06

SSK