我是JPA的新手,我尝试使用Criteria Query进行动态查询。
我的代码:
CriteriaBuilder cb = crudService.getEm().getCriteriaBuilder();
// query 1
CriteriaQuery<MsCountry> cq = cb.createQuery(MsCountry.class);
Root<MsCountry> myObj = cq.from(MsCountry.class);
Join<MsCountry, MsCurrency> join = myObj.join(MsCountry_.currencyId, JoinType.INNER);
// query 2
CriteriaQuery<Long> cqCount = cb.createQuery(Long.class);
Root<MsCountry> rootCount = cqCount.from(MsCountry.class);
cqCount.select(cb.count(rootCount));
//filtering
List<Predicate> predicates = new ArrayList<Predicate>();
for (Entry<String, String> filter : filters.entrySet()) {
String[] filterField = filter.getKey().split("\\.", 2);
Path path = filterField.length == 1 ? myObj.get(filterField[0]) : join.get(filterField[1]);
predicates.add(filter.getValue().matches("[0-9]+")
? cb.equal(path, Long.valueOf(filter.getValue()))
: cb.like(path, "%" + filter.getValue() + "%"));
}
//use same where for both query
cq.where(predicates.toArray(new Predicate[0]));
cqCount.where(predicates.toArray(new Predicate[0]));
List<MsCountry> = entityManager.createQuery(cq).setFirstResult(first).setMaxResults(pageSize).getResultList();
int countResult = entityManager.createQuery(cqCount).getSingleResult().intValue();
//query 1 = the result is correct (for a sample get 4 row)
SELECT t1.country_id AS a1, t1.country_code AS a2, t1.country_description AS a3, t1.country_name AS a4, t1.currency_id AS a5 FROM ms_currency t0, ms_country t1 WHERE (t1.country_code LIKE ? AND (t0.currency_id = t1.currency_id)) LIMIT ?, ?
//query 2 = the result is wrong (not 4 but 72)
SELECT COUNT(t0.country_id) FROM ms_country t0, ms_country t2, ms_currency t1 WHERE (t2.country_code LIKE ? AND (t1.currency_id = t2.currency_id))
我需要将计数数据设置为setRowCount。
如何解决这个或任何其他想法,是否有两个查询可以组合到一个数据库调用?
提前感谢您的帮助