Hibernate ProjectionList用于从具有列值限制的表中获取计数

时间:2016-08-10 06:48:09

标签: java hibernate projection

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

考虑上面的模型类(Books),它的类别变量为A,B,C。

它存储在表格中 - 'books',列名为'book_id','book_name','category'(类别值为A或B或C)。

使用 Hibernate ProjectionList ,我想

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

将其分配给3个单独的int值countA,countB,countC

2 个答案:

答案 0 :(得分:0)

只是为了展示其中一种方法,将How do we count rows using Hibernate?Doing an "IN" query with Hibernate相结合 {{3}}

Integer count = (Integer) session.CreateQuery("select count(*) from Books where category = ?1")
     .query.setParameter(1, "A")
     .uniqueResult();

答案 1 :(得分: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];
                        }
                    }
                }