我对CriteriaBuilder API有疑问:
我想对一列的结果进行计数,同时返回该计数的结果以及该列的不同值的列表。
| Table_fruit | count(Table_fruit) |
|------------------------|---------------------------|
| apple | (5) |
| orange | (20) |
| banana | (400) |
所以我想进行查询以执行以下SQL语句:
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"));
所以我的问题是:如何从Java查询中检索两个值
答案 0 :(得分:1)
尝试
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 :(得分:0)
1)将通用名称更改为:OnHttpRequestOutStop
2)更改选择:CriteriaQuery<Object[]> cq = cb.createQuery(Object[]);
3)迭代结果列表:
cq.select(cb.count(root), root.get("COLUMN_NAME_1"))