tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Hibernate > Hibernate Query Language > Distinct Clause

Distinct Clause 

The following example shows using HQL distinct clause. Refer first example for the configuration and mapping.

File Name  :  
com/bethecoder/tutorials/hibernate/basic/tests/HQLDistinctTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.hibernate.basic.tests;

import java.util.List;
import org.hibernate.Session;
import com.bethecoder.tutorials.hibernate.basic.util.HibernateUtil;

public class HQLDistinctTest {

  /**
   @param args
   */
  public static void main(String[] args) {

    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    
    String HQL_QUERY = "select count(distinct comp.name), count(comp.name) from Company comp";
    Object[] row = (Object[]) session.createQuery(HQL_QUERY).uniqueResult();    

    System.out.println("Unique Company name Count : " + row[0]);
    System.out.println("Company name Count : " + row[1]);
    
    
    HQL_QUERY = "select distinct comp.name from Company comp";
    List<?> uniqueAddress = session.createQuery(HQL_QUERY).list();
    System.out.println("Unique Company names : " + uniqueAddress);
    
    HQL_QUERY = "select comp.name from Company comp";
    List<?> address = session.createQuery(HQL_QUERY).list();
    System.out.println("Company names : " + address);
    
    session.getTransaction().commit();
    session.close();
  }

}
   

It gives the following output,
Unique Company name Count : 9
Company name Count : 10
Unique Company names : [PQR, ABC, MNO, IJK, ART, RNK, AOQ, BQO, CFR]
Company names : [PQR, ABC, MNO, IJK, ART, RNK, AOQ, BQO, CFR, CFR]



 
  


  
bl  br