I have an HQL query, but it has many where conditions. 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. 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 .
and for distinct you can use
setProjection(Projections.distinct(Projections.property("nameOfField")));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.