The following examples takes you through a series of aggregate functions, where clauses, group by and order by criteria using hibernate.
Min( ):
Restrictions based Query (AND, OR, comparators):
GROUP BY:
Order By:
MAX( ) :
public int getMaxDeptId() {
int maxId = 0;
HibernateTemplate ht = new HibernateTemplate(sessionFactory);
DetachedCriteria criteria = DetachedCriteria
.forClass(Departments.class);
criteria.setProjection(Projections.max("deptId"));
List result = ht.findByCriteria(criteria);
maxId = (Integer) result.get(0);
return maxId;
}
Min( ):
public int getMinDeptId() {
int minId = 0;
HibernateTemplate ht = new HibernateTemplate(sessionFactory);
DetachedCriteria criteria = DetachedCriteria
.forClass(Departments.class);
criteria.setProjection(Projections.min("deptId"));
List result = ht.findByCriteria(criteria);
minId = (Integer) result.get(0);
return minId;
}
Restrictions based Query (AND, OR, comparators):
public List getCustomDepartments() {
ArrayList values = new ArrayList();
values.add("java");
values.add("hibernate");
values.add("Spring");
values.add("XML");
HibernateTemplate ht = new HibernateTemplate(sessionFactory);
DetachedCriteria criteria = DetachedCriteria
.forClass(Departments.class);
criteria.add(Restrictions.in("deptName", values));
criteria.add(Restrictions.and(Restrictions.in("deptName", values),
Restrictions.le("deptId", 3)));
criteria.addOrder(Order.desc("deptName"));
return ht.findByCriteria(criteria);
}
GROUP BY:
public void getDepartmentsInEachYear() {
HibernateTemplate ht = new HibernateTemplate(sessionFactory);
DetachedCriteria criteria = DetachedCriteria
.forClass(Departments.class);
criteria.setProjection(Projections.groupProperty("yearStarted"));
System.out.println(">>>>" + ht.findByCriteria(criteria).size());
}
Order By:
public ListgetDepartments(boolean ascending) { HibernateTemplate ht = new HibernateTemplate(sessionFactory); DetachedCriteria criteria = DetachedCriteria .forClass(Departments.class); if (!ascending) { criteria.addOrder(Order.desc("deptName")); } else { criteria.addOrder(Order.asc("deptName")); } return ht.findByCriteria(criteria); }
Back To Top
Posted in: