如何在Java的JPA查询中使用IN子句?

时间:2019-03-20 12:57:49

标签: java spring spring-boot jpa spring-data-jpa

我在下面有以下代码:

public Optional<KoKur> getExchangeRateFromList(final Integer code, List<KotukOdeme> paymentList){

    List<LocalDate> paymentDateList = null;
    for(KotukOdeme kotukOdeme : paymentList){
        paymentDateList.add(kotukOdeme.getOdemeTarihi());
    }

    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<KoKur> query = cb.createQuery(KoKur.class);
    Root<KoKur> koKurRoot = query.from(KoKur.class);
    query.where(
            cb.and(
                    cb.equal(koKurRoot.get("dovizTip"), code)

            )

    );
    TypedQuery<KoKur> typedQuery = entityManager.createQuery(query);
    List<KoKur> koKurList = typedQuery.getResultList();

    return koKurList.isEmpty() ? Optional.empty() : Optional.of(koKurList.get(0));
}

我正在收集paymentDateList中的本地日期列表,我想在查询中将它们添加为IN子句。因此,在“代码”旁边,我也想在AND子句旁边添加IN。当我如下添加时,IDE给我错误;

cb.in(koKurRoot.get("tarih"), paymentDateList) 

我该怎么做?

2 个答案:

答案 0 :(得分:1)

使用cb.in(koKurRoot.get("tarih")).value(paymentDateList)

答案 1 :(得分:0)

这应该有效。如果需要,可向谓词数组添加其他条件

List<Predicate> predicates = new ArrayList<>();    
predicates.add(query.get("tarih").in(paymentDateList))

query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
return entityManager.createQuery(query).getResultList();