I am new in JPA, I have try to make Dynamic query with Criteria Query.
my code :
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))
I need the count data to setRowCount.
How to solve this or any other idea , is there posibble two queries be combined to one call to the database?
Thank you in advance for your help