Spring Data JPA findAll with different EntityGraph
Asked Answered
A

2

8

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

Amie answered 3/5, 2020 at 23:29 Comment(2)
You can use an EntityGraph as a parameter : #50950156Marabelle
Perfect, I didn't know you could pass the entity graph as a parameter! thanks!Amie
S
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.

Spectra answered 4/5, 2020 at 3:53 Comment(4)
Thank you, your answer has been very useful to me. Thanks!Amie
You can accept the answer so that others know the sameSpectra
I can't seem to find EntityGraphJpaSpecificationExecutor, where did you get it from?Blacksnake
@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.2Spectra
V
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);
    }
}
Viceregal answered 6/10, 2023 at 7:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.