dfche
dfche

Reputation: 3693

Can I have one @Query for multiple JPA repository methods with different signature and return type?

For example, we have a JPA repository containing three methods looking for exactly the same DB selection, but presenting it in different forms:

public interface UserRepository extends JpaRepository<User, Long> {

   ... some repository methods ...

   List<User> findUsersByCustomCriteria(String criteria);

   Set<User> findUsersByCustomCriteria(String criteria, Sort sort);

   Page<User> findUsersByCustomCriteria(String criteria, Pageable pageable);
}

and a query

@Query("SELECT u FROM User u WHERE ...");

Is there an easy way to avoid repeating the same query 3 times, excepts @NamedQuery in User class?

Upvotes: 1

Views: 862

Answers (1)

dfche
dfche

Reputation: 3693

Well, I realized that it is possible to declare query as String. But more elegant way suggestions are still welcome, may be I am missing something.

public interface UserRepository extends JpaRepository<User, Long> {
   String QUERY_TEXT = "SELECT u FROM User u WHERE ...";

   ... some repository methods ...

   @Query(QUERY_TEXT)
   List<User> findUsersByCustomCriteria(String criteria);

   @Query(QUERY_TEXT)
   Set<User> findUsersByCustomCriteria(String criteria, Sort sort);

   @Query(QUERY_TEXT)
   Page<User> findUsersByCustomCriteria(String criteria, Pageable pageable);
}

Upvotes: 1

Related Questions