JPA - How to add same query to a repository twice

Viewed 80

I am trying to use the same query more than once, with different options set by annotations. Similar to:

@EntityGraph(attributePaths = {"books"})
Optional<User> findById(long id);

@EntityGraph(attributePaths = {"courses"})
Optional<User> findById(long id);  

Optional<A_Projection> findById(long id);

Is there a way to add a prefix or a postfix to the method name, such that I can have different function signatures but it would be interpreted as same JPA query to avoid using @Query? Such as:

@EntityGraph(attributePaths = {"books"})
Optional<User> findByIdQ1(long id);  //Q1,Q2,Q3 prefixes help distinguish these methods

@EntityGraph(attributePaths = {"courses"})
Optional<User> findByIdQ2(long id);  //but they mess up the JPA syntax

Optional<A_Projection> findByIdQ3(long id);

As an example, for Projection case, this is a valid syntax:

Optional<A_Projection> findByIdByProjection(long id);
2 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 findOne with entity graph.

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

I found what I was looking for. Apparently, JPA searches for find....By in derived queries. Therefore, you can add whatever between these clauses:

Optional<User> findWithBooksById(long id);  //Q1,Q2,Q3 prefixes help distinguish these methods

@EntityGraph(attributePaths = {"courses"})
Optional<User> findWithWhateverById(long id);  //but they mess up the JPA syntax

Optional<A_Projection> findById(long id);

From Spring documentation:

Any text between find (or other introducing keywords) and By is considered to be descriptive unless using one of the result-limiting keywords such as a Distinct to set a distinct flag on the query to be created or Top/First to limit query results.

Related