简体   繁体   中英

How to use IN clause in JPA query in Java?

I have this code below:

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

I am collecting list of localdates in paymentDateList, I want to add these as IN clause in my query. So beside "code", also i want to add IN next to my AND clause. When I add like below IDE gives me error;

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

How can I do that ?

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

This should work. Add other conditions to predicates array if you need

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

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