
In general group by clause is used with aggregate functions for grouping the result. It is also a powerful option of sorting as it returns the list grouping in ascending order. It allows the Hibernate to fetch information from the database and group by them under the specified attribute.
package net.roseindia.main;
import java.util.*;
import net.roseindia.table.Employee;
import net.roseindia.util.HibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class HQLGroupBy{
public static void main(String []args){
SessionFactory sessionFactory =HibernateUtil.getSessionFactory();
Session session=sessionFactory.openSession();
String hql="Select emp.name FROM Employee emp GROUP BY name";
Query query=session.createQuery(hql);
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List objectList = query.list();
Iterator iterator = objectList.iterator();
while(iterator.hasNext()){
Map map = (Map)iterator.next();
System.out.println(map.get("0"));
}
session.close();
}
}
Output :
Hibernate: select employee0_.name as col_0_0_ from employee employee0_ group by employee0_.name Mandy Ron Roxi Som