9

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

2

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, your answer has been very useful to me. Thanks!
You can accept the answer so that others know the same
I can't seem to find EntityGraphJpaSpecificationExecutor, where did you get it from?
@La Hai, You need to add dependency for it from https://mvnrepository.com/artifact/com.cosium.spring.data/spring-data-jpa-entity-graph/2.4.2
0

You can create two default methods in your repository with same signature like this:

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

    @EntityGraph(attributePaths = { "roles" })
    default List<Roles> findAllByRoles(Specification sp){
       return findAll(sp);
    }

    @EntityGraph(attributePaths = { "groups" })
    default List<Roles> findAllByGroups(Specification sp){
       return findAll(sp);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.