Search code examples
javajpaormcriteriacriteriaquery

JPA count(*) using CriteriaBuilder. How to use CriteriaBuilder to retrive the count(*) column


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


Solution

  • 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"));