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
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.