Close

Eliminating Duplicate Values by using SELECT-DISTINCT statement

[Last Updated: Mar 30, 2018]

The SELECT DISTINCT statement is used to return only unique results .

Example

The Entity

@Entity
public class Employee {
    @Id
    @GeneratedValue
    private long id;
    private String name;
    private String dept;
    .............
}

Using Query

public class ExampleMain {
    private static EntityManagerFactory entityManagerFactory =
            Persistence.createEntityManagerFactory("example-unit");

    public static void main(String[] args) {
        try {
            persistEmployees();
            findDistinctDept();
        } finally {
            entityManagerFactory.close();
        }
    }

    public static void persistEmployees() {
        Employee employee1 = Employee.create("Diana", "IT");
        Employee employee2 = Employee.create("Rose", "Admin");
        Employee employee3 = Employee.create("Denise", "IT");
        EntityManager em = entityManagerFactory.createEntityManager();
        em.getTransaction().begin();
        em.persist(employee1);
        em.persist(employee2);
        em.persist(employee3);
        em.getTransaction().commit();
        em.close();
    }

    private static void findDistinctDept() {
        EntityManager em = entityManagerFactory.createEntityManager();
        Query query = em.createQuery("SELECT DISTINCT e.dept FROM Employee e");
        List<String> resultList = query.getResultList();
        resultList.forEach(System.out::println);
        em.close();
    }
}
IT
Admin

Example Project

Dependencies and Technologies Used:

  • h2 1.4.197: H2 Database Engine.
  • hibernate-core 5.2.13.Final: The core O/RM functionality as provided by Hibernate.
    Implements javax.persistence:javax.persistence-api version 2.1
  • JDK 1.8
  • Maven 3.3.9

SELECT-DISTINCT Statement Example Select All Download
  • select-distinct-statement-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ExampleMain.java
          • resources
            • META-INF

    See Also