【问题标题】:How to Write JPA FindBy Query for AND and OR conditions如何为 AND 和 OR 条件编写 JPA FindBy 查询
【发布时间】:2021-10-29 11:01:58
【问题描述】:

我想从 JPA findBy 方法创建一个 JPA 查询

select * from somTable where Col1 =1
    and (col2 > 0 or col2 = 0)
    and (col3 > 0 or col3 = 0)
    and (col4 >0 or col4 =0)
    and (col5 >0 or col5 =0)

【问题讨论】:

    标签: jpa spring-data-jpa


    【解决方案1】:

    有多种方法可以解决它

    • Spring Data JPA 方式,使用@QueryNamed Parameters

      public interface SomeTableRepository extends JpaRepository<SomeTable, Long> {   
          @Query("SELECT t FROM SomeTable t WHERE t.col1 = :col1 AND t.col2 >= :col2 AND t.col3 >= :col3")
          List<SomeTable> findAllByCol(@Param("col1") int col1, @Param("col2") int col2, @Param("col3") int col3);
      }
      
    • JPA 方式,使用JPA Criteria Queries

      @Repository
      @Transactional
      public class SomeTableJpaRepository {
      
          @PersistenceContext
          EntityManager entityManager;
      
          public List<SomeTable> findAll(int col1, int col2, int col3, int col4, int col5) {
              CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
              CriteriaQuery<SomeTable> criteriaQuery = criteriaBuilder.createQuery(SomeTable.class);
              Root<SomeTable> itemRoot = criteriaQuery.from(SomeTable.class);
      
              List<Predicate> predicates = new ArrayList<>();
      
              Predicate predicateCol1
                    = criteriaBuilder.equal(itemRoot.get("col1"), col1);
              predicates.add(predicateCol1);
      
              Predicate predicateCol2
                    = criteriaBuilder.greaterThanOrEqualTo(itemRoot.get("col2"), col2);
              predicates.add(predicateCol2);
      
              Predicate predicateCol3
                    = criteriaBuilder.greaterThanOrEqualTo(itemRoot.get("col3"), col3);
              predicates.add(predicateCol3);
      
              // ...
              criteriaQuery.select(itemRoot).where(predicates.toArray(new Predicate[]{}));
      
              return entityManager.createQuery(criteriaQuery).getResultList();
          }
      }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      相关资源
      最近更新 更多