简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM