如果参数为null则选择所有记录,否则返回JPA Criteria查询中的specfic项

时间:2017-07-03 12:44:39

标签: java jpa criteria

我正在使用JPA,如果搜索字段为空,我想编写搜索查询以获取所有记录,如果搜索参数不为null,则应用条件查询。

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;

由于

1 个答案:

答案 0 :(得分:0)

我最终使用Criteria API获得了解决方案。看看下面的代码。

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