[英]Restrict selected fields using Hibernate Criteria projection
I have an HQL query, but it has many where conditions. 我有一个HQL查询,但是它有许多条件。 So I decided to use Hibernate Criteria.
因此,我决定使用休眠标准。
Here is my query: 这是我的查询:
select distinct u.employee.id,u.employee.name,u.employee.address.phone from user u.
I tried it using the Criteria Project.property. 我使用Criteria Project.property进行了尝试。 But it gives an error.
但它给出了一个错误。 Is it possible to write Hibernate Criteria for this query?
是否可以为此查询编写休眠条件?
Criteria cr = session.createCriteria(User.class)
.setProjection(Projections.projectionList()
.add(Projections.property("employee.id"), "id")
.add(Projections.property("employee.name"), "Name"));
List<User> list = cr.list();
Few more examples. 几个例子。
Criteria cr = session.createCriteria(Employee.class);
// To get total row count. //获取总行数。
cr.setProjection(Projections.rowCount());
// To get average of a property. //获得属性的平均值。
cr.setProjection(Projections.avg("salary"));
// To get distinct count of a property. //获得属性的不同计数。
cr.setProjection(Projections.countDistinct("firstName"));
// To get maximum of a property. //获得最大的属性。
cr.setProjection(Projections.max("salary"));
// To get minimum of a property. //获得最少的属性。
cr.setProjection(Projections.min("salary"));
// To get sum of a property. //获取一个属性的总和。
cr.setProjection(Projections.sum("salary"));
List<User> users = (List<User>) dbSession.createCriteria(User.class)
.add(Restrictions.eq("nameOfFieldInUserClass", value))
.list();
"nameOfFieldInUserClass" is name of restriction field in User, not name of column in DB . “ nameOfFieldInUserClass”是User中限制字段的名称 , 而不是DB中列的名称 。
and for distinct you can use 对于不同的可以使用
setProjection(Projections.distinct(Projections.property("nameOfField")));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.