【问题标题】:Hibernate ProjectionList for getting count from table with column value restrictionsHibernate ProjectionList 用于从具有列值限制的表中获取计数
【发布时间】:2016-12-16 09:48:37
【问题描述】:
class Books{
    private int bookId; //primary key
    private String bookName;
    Private String category;
}

考虑上面的模型类(书籍),它的类别变量为 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

【问题讨论】:

  • @MichaelDibbets 您的链接回答了整个表格的投影计数,没有限制
  • 检查第二个答案...或第三个,或第四个或第五个...
  • @MichaelDibbets 我在那里没有发现任何限制。找不到我提出的问题的解决方案。
  • 如果您使用原生查询并使用GROUP BY 获取所有类别的总和会怎样?

标签: java hibernate projection


【解决方案1】:
                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];
                        }
                    }
                }

【讨论】:

    【解决方案2】:

    只是为了展示其中一种方法,在How do we count rows using Hibernate? 中链接并与 Doing an "IN" query with Hibernate

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

    【讨论】:

    • 你的回答给了我总数。我希望它作为一个单独的计数@MichaelDibbets
    • 你真的希望被勺子喂食吗?这就是我提供的所有帮助。看在上帝的份上,学习如何构建查询。
    • 我知道,看看我编辑的答案,但这就像你阅读文档后看到的第一件事......查询、选择等重要的地方。
    • 在@MichaelDibbets下方找到我的答案
    猜你喜欢
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多