-2
class Books{
    private int bookId; //primary key
    private String bookName;
    Private String category;
}

Consider the above model class(Books) where it has category variable as A,B,C.

It is stored in table - 'books' with column names 'book_id' ,'book_name' , 'category'(category values will be either A or B or C).

Using Hibernate ProjectionList, I would like to have

1.count of book_id(from DB table) with category value as A 
2.count of book_id(from DB table) with category value as B 
3.count of book_id(from DB table) with category value as C

Assign it to a 3 separate int values countA,countB,countC

2 Answers2

0

Just to show one of the methods to do it, als linked in How do we count rows using Hibernate? combined with Doing an "IN" query with Hibernate

Integer count = (Integer) session.CreateQuery("select count(*) from Books where category = ?1")
     .query.setParameter(1, "A")
     .uniqueResult();
Community
  • 1
  • 1
Tschallacka
  • 27,901
  • 14
  • 88
  • 133
0
                Criteria cr = session.createCriteria(Book.class);
                ProjectionList projList = Projections.projectionList();        
                projList.add(Projections.groupProperty("category"));
                projList.add(Projections.count("category").as("count"));
                cr.setProjection(projList);
                List<Object[]> rows = cr.list();
                if(rows.size()>0){
                    for(Object[] itr : rows){
                        if("A".equalsIgnoreCase(((String) itr[0]).trim())){
                            int countA = (long)itr[1];
                        }
                        if("B".equalsIgnoreCase(((String) itr[0]).trim())){
                            int countB = (long)itr[1];
                        }
                        if("C".equalsIgnoreCase(((String) itr[0]).trim())){
                            int countC = (long)itr[1];
                        }
                    }
                }