
How do you count distinct value in HQL?

count(distinct fieldName) returns number of distinct value of the table under specified field name.
Example :
package net.roseindia.main;
import net.roseindia.util.HibernateUtil;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class DistinctCountHQL {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
String countHql = "Select count(distinct salary) FROM Employee emp";
Query countQuery = session.createQuery(countHql);
System.out.println("Number of Employee: " + countQuery.list().get(0));
}
}
Output:
Hibernate: select count(distinct employee0_.salary) as col_0_0_ from employee employee0_ Number of Employee having distinct salary : 3
Description: This example counts the number of employee having distinct salary by using count(distinct salary).
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.