The SELECT DISTINCT statement is used to return only unique results .
@Entity public class Employee { @Id @GeneratedValue private long id; private String name; private String dept; ............. }
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(); } }
ITAdmin
Dependencies and Technologies Used: