简体   繁体   中英

Select all records if parameter is null else return specfic item in JPA Criteria query

I am using JPA and I want to write search query for fetching all the records if search field is empty and if search parameter is not null then apply criteria query.

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<String> query = cq.from(String.class);
cq.where(cb.equal(query.get("id"), '1234567'));

TypedQuery<String> q = entityManager.createQuery(cq);
List<String> results = q.getResultList();
return results;

Thanks

I had a solution finally using Criteria API. Have a look at the code below.

public List < Object > retrieveAll(Object obj) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery < Object > cq = cb.createQuery(Object.class);
    Root < Object > objQuery = cq.from(Object.class);

    List < Predicate > predicates = new ArrayList < Predicate > ();

    // You can add as many as Predicate you want.
    if (null != obj.getName() && !obj.getName().isEmpty()) {
        predicates.add(cb.equal(objQuery.get("Name"), obj.getName()));
    }

    List < Object > results = new ArrayList < Object > ();
    if (!predicates.isEmpty()) {
        cq.select(objQuery).where(predicates.toArray(new Predicate[] {}));
        cq.orderBy(cb.asc(objQuery.get("Name")));
        results = entityManager.createQuery(cq).getResultList();
    } else {
        results = entityManager.createQuery("from Emplyee ORDER BY Name asc").getResultList();
    }
    return results;
}

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