0

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

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
Ahmed Aziz
  • 380
  • 1
  • 5
  • 17

2 Answers2

1

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"));
Reza Nasiri
  • 1,360
  • 1
  • 6
  • 19
0

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
}
Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63