Query creation in Spring Data - dynamic where clause

前端 未结 3 1487
没有蜡笔的小新
没有蜡笔的小新 2021-01-06 03:47

Is there a way in Spring data to dynamically form the where clause?

What I want to do is have a method (which is like the findBy / get method) which runs a WHERE and

相关标签:
3条回答
  • 2021-01-06 04:10

    Another solution: You can extend your JPA repo interface using custom fragment interfaces.

    1. Define your custom methods on a new interface

      public interface PersonFragRepository {
          List<User> findPersonByWhatever(
              String firstName, String lastName, String age, String gender);
      }
      
    2. Provide the implementation

      public class PersonFragRepositoryImpl implements PersonFragRepository {
          @PersistenceContext
          private EntityManager entityManager;
      
          @Override
          List<User> findPersonByWhatever(
              String firstName, String lastName, String age, String gender) {
             ...
          }
      }
      
    3. Extends your JPA interface

      public interface PersonRepository
          extends JpaRepository<Person, Integer>, PersonFragRepository
      
    0 讨论(0)
  • 2021-01-06 04:19

    A even more simple option is to test if the parameter is null right in the JPQL query:

    Exemple from my project:

    @Query("select m from MessageEntity m " +
                "join fetch m.demandeAnalyseEntities d " +
                "where (:patientId is null or d.noPtn= :patientId) " +
                " and " +
                " ( :labNbr is null or d.noLab= :labNbr) " +
                " and " +
                " ( :reqDate is null or d.dteReq= :reqDate) " +
                " and " +
                " ( :reqNum is null or d.noReq= :reqNum) "
        )
        List<MessageEntity> findMessagesWithDemandesOnly(@Param("patientId") Long pid,
                                                         @Param("labNbr") Integer labNo,
                                                         @Param("reqDate") String reqDate,
                                                         @Param("reqNum") Integer reqNum,
                                                         Pageable pageable);
    
    0 讨论(0)
  • 2021-01-06 04:31

    Take a look at JPA Specification and Predicate, and Even better QueryDSL, there both supported by spring data repositories. This article provide an example: http://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

    0 讨论(0)
提交回复
热议问题