BAEL-2227 JPA Criteria Queries In Clause (#5606)

* BAEL-2159: Mini Article on "Separate double into integer and decimal parts"

* BEAL-2227: JPA Criteria Query In clause - Tutorial.

* Minor Fix: Changed type of Predicate.

* BAEL-2227: Code Review Comments: Extracted criteriaBuilder to a field. Refactored a private method to create criteria query.

* BAEL-2227: Fixed spelling mistakes in the code.
This commit is contained in:
Akash Pandey 2018-11-04 21:33:56 +05:30 committed by maibin
parent b9d30cef53
commit e924ed163d
4 changed files with 222 additions and 0 deletions

View File

@ -23,6 +23,14 @@ public class DeptEmployee {
this.department = department;
}
public DeptEmployee(String name, String employeeNumber, String designation, Department department) {
super();
this.name = name;
this.employeeNumber = employeeNumber;
this.designation = designation;
this.department = department;
}
public long getId() {
return id;
}

View File

@ -0,0 +1,15 @@
package com.baeldung.hibernate.jpacriteriabuilder.service;
import java.util.List;
import com.baeldung.hibernate.entities.DeptEmployee;
public interface EmployeeSearchService {
List<DeptEmployee> filterbyDesignationUsingCriteriaBuilder(List<String> designaitons);
List<DeptEmployee> filterbyDesignationUsingExpression(List<String> aurhors);
List<DeptEmployee> searchByDepartmentQuery(String query);
}

View File

@ -0,0 +1,77 @@
package com.baeldung.hibernate.jpacriteriabuilder.service;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaBuilder.In;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Subquery;
import com.baeldung.hibernate.entities.Department;
import com.baeldung.hibernate.entities.DeptEmployee;
public class EmployeeSearchServiceImpl implements EmployeeSearchService {
private EntityManager entityManager;
private CriteriaBuilder criteriaBuilder;
public EmployeeSearchServiceImpl(EntityManager entityManager) {
this.entityManager = entityManager;
this.criteriaBuilder = entityManager.getCriteriaBuilder();
}
@Override
public List<DeptEmployee> filterbyDesignationUsingCriteriaBuilder(List<String> designations) {
CriteriaQuery<DeptEmployee> criteriaQuery = createCriteriaQuery(DeptEmployee.class);
Root<DeptEmployee> root = criteriaQuery.from(DeptEmployee.class);
In<String> inClause = criteriaBuilder.in(root.get("designation"));
for (String designaiton : designations) {
inClause.value(designaiton);
}
criteriaQuery.select(root)
.where(inClause);
TypedQuery<DeptEmployee> query = entityManager.createQuery(criteriaQuery);
return query.getResultList();
}
@Override
public List<DeptEmployee> filterbyDesignationUsingExpression(List<String> designations) {
CriteriaQuery<DeptEmployee> criteriaQuery = createCriteriaQuery(DeptEmployee.class);
Root<DeptEmployee> root = criteriaQuery.from(DeptEmployee.class);
criteriaQuery.select(root)
.where(root.get("designation")
.in(designations));
TypedQuery<DeptEmployee> query = entityManager.createQuery(criteriaQuery);
return query.getResultList();
}
@Override
public List<DeptEmployee> searchByDepartmentQuery(String searchKey) {
CriteriaQuery<DeptEmployee> criteriaQuery = createCriteriaQuery(DeptEmployee.class);
Root<DeptEmployee> emp = criteriaQuery.from(DeptEmployee.class);
Subquery<Department> subquery = criteriaQuery.subquery(Department.class);
Root<Department> dept = subquery.from(Department.class);
subquery.select(dept)
.distinct(true)
.where(criteriaBuilder.like(dept.get("name"), new StringBuffer("%").append(searchKey)
.append("%")
.toString()));
criteriaQuery.select(emp)
.where(criteriaBuilder.in(emp.get("department"))
.value(subquery));
TypedQuery<DeptEmployee> query = entityManager.createQuery(criteriaQuery);
return query.getResultList();
}
private <T> CriteriaQuery<T> createCriteriaQuery(Class<T> klass) {
return criteriaBuilder.createQuery(klass);
}
}

View File

@ -0,0 +1,122 @@
package com.baeldung.hibernate.jpacriteriabuilder;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.hibernate.HibernateUtil;
import com.baeldung.hibernate.entities.Department;
import com.baeldung.hibernate.entities.DeptEmployee;
import com.baeldung.hibernate.jpacriteriabuilder.service.EmployeeSearchService;
import com.baeldung.hibernate.jpacriteriabuilder.service.EmployeeSearchServiceImpl;
public class EmployeeSearchServiceIntegrationTest {
private EntityManager entityManager;
private EmployeeSearchService searchService;
private Session session;
@Before
public final void setup() throws HibernateException, IOException {
session = HibernateUtil.getSessionFactory()
.openSession();
entityManager = session.getEntityManagerFactory()
.createEntityManager();
searchService = new EmployeeSearchServiceImpl(entityManager);
entityManager.getTransaction()
.begin();
Department department = new Department("Pre Sales");
DeptEmployee employee = new DeptEmployee("John Smith", "001", "Manager", department);
entityManager.persist(department);
entityManager.persist(employee);
employee = new DeptEmployee("Ian Evans", "002", "Associate", department);
entityManager.persist(department);
entityManager.persist(employee);
department = new Department("Copporate Sales");
employee = new DeptEmployee("Robert Carter", "003", "Manager", department);
entityManager.persist(department);
entityManager.persist(employee);
employee = new DeptEmployee("John Carter", "004", "Senior Manager", department);
entityManager.persist(employee);
employee = new DeptEmployee("David Guetta", "009", "Associate", department);
entityManager.persist(department);
entityManager.persist(employee);
department = new Department("Post Sales");
employee = new DeptEmployee("Robert Jonas", "005", "Director", department);
entityManager.persist(department);
entityManager.persist(employee);
employee = new DeptEmployee("John Ferros", "006", "Junior Associate", department);
entityManager.persist(department);
entityManager.persist(employee);
department = new Department("Client Support");
employee = new DeptEmployee("Robert Mcclements", "007", "Director", department);
entityManager.persist(department);
entityManager.persist(employee);
employee = new DeptEmployee("Peter Parker", "008", "Manager", department);
entityManager.persist(department);
entityManager.persist(employee);
}
@After
public final void teardown() {
entityManager.getTransaction()
.rollback();
entityManager.close();
}
@Test
public final void givenCriteriaQuery_whenSearchedUsingCriteriaBuilderWithListofAuthors_thenResultIsFilteredByAuthorNames() {
List<String> designations = new ArrayList<String>() {
{
add("Manager");
add("Senior Manager");
add("Director");
}
};
List<DeptEmployee> result = searchService.filterbyDesignationUsingCriteriaBuilder(designations);
assertEquals("Number of Employees does not match with expected.", 6, result.size());
assertThat(result.stream()
.map(DeptEmployee::getDesignation)
.distinct()
.collect(Collectors.toList()), containsInAnyOrder(designations.toArray()));
}
@Test
public final void givenCriteriaQuery_whenSearchedUsingExpressionWithListofAuthors_thenResultIsFilteredByAuthorNames() {
List<String> designations = new ArrayList<String>() {
{
add("Manager");
add("Senior Manager");
add("Director");
}
};
List<DeptEmployee> result = searchService.filterbyDesignationUsingExpression(designations);
assertEquals("Number of Employees does not match with expected.", 6, result.size());
assertThat(result.stream()
.map(DeptEmployee::getDesignation)
.distinct()
.collect(Collectors.toList()), containsInAnyOrder(designations.toArray()));
}
@Test
public final void givenCriteriaQuery_whenSearchedDepartmentLike_thenResultIsFilteredByDepartment() {
List<DeptEmployee> result = searchService.searchByDepartmentQuery("Sales");
assertEquals("Number of Employees does not match with expected.", 7, result.size());
// assertThat(result.stream().map(DeptEmployee::getDesignation).distinct().collect(Collectors.toList()), containsInAnyOrder(designations.toArray()));
}
}