Gabriele Muscas
Gabriele Muscas

Reputation: 2235

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

Upvotes: 9

Views: 4943

Answers (3)

cagliostro92
cagliostro92

Reputation: 71

This is the spring-data-jpa vanilla solution using FetchableFluentQuery:

myJpaSpecExecRepo.findBy(mySpec, fetchable ->
  fetchable.project("lazyAttr1","lazyAttr2").page(page))

Upvotes: 1

sinclairjaza
sinclairjaza

Reputation: 1

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);
    }
}

Upvotes: 0

SSK
SSK

Reputation: 3766

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.

Upvotes: 4

Related Questions