I have a question about CriteriaBuilder API:
I would like to count the results of a column with returning back the result of that counting and the list of the distinct values of that column.
| Table_fruit | count(Table_fruit) |
|------------------------|---------------------------|
| apple | (5) |
| orange | (20) |
| banana | (400) |
So I want to make a query that will do this SQL statement:
select distinct COLUMN_NAME_1, count(COLUMN_NAME_1)
from TABLE_NAME
where COLUMN_NAME_2= 'value'
group by COLUMN_NAME_1;
CriteriaBuilder cb = getCriteriaBuilder();
CriteriaQuery<Fruit> cq = cb.createQuery(Fruit.class);
Root<TABLE_NAME> root = cq.from(Fruit.class);
List<Predicate> predicates = new ArrayList<>();
predicates.add(cb.equal(root.get("COLUMN_NAME_2"), value));
cq.where(predicates.toArray(new Predicate[predicates.size()]));
// how to select the COUNT(*) from the table here?
cq.select(root.get("COLUMN_NAME_1")).distinct(true);
cq.groupBy(root.get("COLUMN_NAME_1"));
So my question is: how to retrieve the two values from the query in Java
try this
cq.multiselect(root.get("COLUMN_NAME_1"), cb.count(root.get("COLUMN_NAME_1"));
// add your predicates here
cq.groupBy(root.get("COLUMN_NAME_1"));
1) Change the generic to: CriteriaQuery<Object[]> cq = cb.createQuery(Object[]);
2) Change the select: cq.select(cb.count(root), root.get("COLUMN_NAME_1"))
3) Iterate the result list:
List<Object[]> results = em.createQuery(cq).getResultList();
for (Object[] result : results) {
// actions
}
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.