hibernate sql

本文通过具体的SQL和HQL查询代码示例,展示了如何使用分组查询来获取特定的数据统计结果。其中包括了直接使用SQL进行查询的方式,以及利用Hibernate Query Language (HQL)配合Criteria API实现相同目标的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

String query = "select u.buyer_id, count(qu.id) from users u, Quotation qu where u.id = qu.buyer_user_id group by u.buyer_id";
Query qu = getSession().createSQLQuery(query);
List<Object[]> res = qu.list();
Map<Long, Long> map = new HashMap<Long, Long>();
for(Object[] item : res){
map.put(((BigInteger)item[0]).longValue(), ((BigInteger)item[1]).longValue());
}
return map;

////////////////////////////////////////
Criteria crit = getSession().createCriteria(Quotation.class, "q")
.createCriteria("user", "u", Criteria.LEFT_JOIN)
.add(Restrictions.eqProperty("q.user.id", "u.id"));
ProjectionList projList = Projections.projectionList();
projList.add(Projections.groupProperty("u.buyer.id"));
projList.add(Projections.count("q.id"));
crit.setProjection(projList);
List<Object[]> res = crit.list();
Map<Long, Long> map = new HashMap<Long, Long>();
for(Object[] item : res){
map.put(((Long)item[0]).longValue(), ((Integer)item[1]).longValue());
}
return map;


////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////

String query = "select buyer_id, count(bill_id) from buyer_billing group by buyer_id";
Query qu = getSession().createSQLQuery(query);
List<Object[]> res = qu.list();
Map<Long, Long> map = new HashMap<Long, Long>();
for(Object[] item : res){
map.put(((BigInteger)item[0]).longValue(), ((BigInteger)item[1]).longValue());
}
return map;
////////////////////////////////////////

Criteria crit = getSession().createCriteria(BuyerBill.class);
ProjectionList projList = Projections.projectionList();
projList.add(Projections.groupProperty("buyerId"));
projList.add(Projections.count("id"));
crit.setProjection(projList);
List<Object[]> res = crit.list();
Map<Long, Long> map = new HashMap<Long, Long>();
for(Object[] item : res){
map.put(((Long)item[0]).longValue(), ((Integer)item[1]).longValue());
}
return map;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值