我们如何在查询中实现Hibernate sqlprojection?
这是我的查询
SELECT sum(total_amount) as total,created_at from order where created_at < DATE_SUB(curdate(), INTERVAL 7 DAY) and doctor_id = 193 GROUP BY created_at
我使用DATE_SUB
实现sqlRestriction
功能,如下所示:
String sqlWhere = "created_at > DATE_SUB(curdate(), INTERVAL "+activityGraph+" DAY) AND doctor_id = "+id +" GROUP BY created_at";
Criteria criteria = Hibernatesession.createCriteria(Order.class);
criteria.add(Restrictions.sqlRestriction(sqlWhere));
但我不知道如何使用Hibernate查询得到字段的总和。
我发现Hibernate中的setProjection
用于获取我们想要的总和,但我不知道如何使用它。此外,我还想使用sqlRestriction
为date_sub
函数编写WHERE条件
因此,我会在单个查询中使用setProjection
和sqlRestriction
。
答案 0 :(得分:3)
你让生活变得困难。为什么不在执行查询之前简单地在Java中计算日期限制?
Date today = DateUtils.truncate(new Date(), Calendar.DATE);
Date limit = DateUtils.addDays(today, -7);
由于查询完全是静态的,为什么要使用Criteria API。 HQL更容易:
String hql = "SELECT sum(o.totalAmount) as total, o.createdAt from Order o"
+ " where o.createdAt < :limit"
+ " and o.doctor.id = 193"
+ " group by o.createdAt";
答案 1 :(得分:2)
criteria.setProjection((Projections.sum("/* name of the mapping variable for total_amount*/")));
答案 2 :(得分:0)
public int getSum() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Criteria criteria = session.createCriteria(Product.class);
criteria.setProjection(Projections.sum("productCount"));
List list = criteria.list();
session.getTransaction().commit();
return (int) list.get(0);
}
//休眠mpping
<property name="productCount" type="int" column="PRODUCT_COUNT"/>