Skip to content

Commit e924ed1

Browse files
akash-pandeymaibin
authored andcommitted
BAEL-2227 JPA Criteria Queries In Clause (eugenp#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.
1 parent b9d30ce commit e924ed1

4 files changed

Lines changed: 222 additions & 0 deletions

File tree

‎persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,14 @@ public DeptEmployee(String name, String employeeNumber, Department department) {
2222
this.employeeNumber = employeeNumber;
2323
this.department = department;
2424
}
25+
26+
public DeptEmployee(String name, String employeeNumber, String designation, Department department) {
27+
super();
28+
this.name = name;
29+
this.employeeNumber = employeeNumber;
30+
this.designation = designation;
31+
this.department = department;
32+
}
2533

2634
public long getId() {
2735
return id;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.baeldung.hibernate.jpacriteriabuilder.service;
2+
3+
import java.util.List;
4+
5+
import com.baeldung.hibernate.entities.DeptEmployee;
6+
7+
public interface EmployeeSearchService {
8+
9+
List<DeptEmployee> filterbyDesignationUsingCriteriaBuilder(List<String> designaitons);
10+
11+
List<DeptEmployee> filterbyDesignationUsingExpression(List<String> aurhors);
12+
13+
List<DeptEmployee> searchByDepartmentQuery(String query);
14+
15+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package com.baeldung.hibernate.jpacriteriabuilder.service;
2+
3+
import java.util.List;
4+
5+
import javax.persistence.EntityManager;
6+
import javax.persistence.TypedQuery;
7+
import javax.persistence.criteria.CriteriaBuilder;
8+
import javax.persistence.criteria.CriteriaBuilder.In;
9+
import javax.persistence.criteria.CriteriaQuery;
10+
import javax.persistence.criteria.Root;
11+
import javax.persistence.criteria.Subquery;
12+
13+
import com.baeldung.hibernate.entities.Department;
14+
import com.baeldung.hibernate.entities.DeptEmployee;
15+
16+
public class EmployeeSearchServiceImpl implements EmployeeSearchService {
17+
18+
private EntityManager entityManager;
19+
private CriteriaBuilder criteriaBuilder;
20+
21+
public EmployeeSearchServiceImpl(EntityManager entityManager) {
22+
this.entityManager = entityManager;
23+
this.criteriaBuilder = entityManager.getCriteriaBuilder();
24+
25+
}
26+
27+
@Override
28+
public List<DeptEmployee> filterbyDesignationUsingCriteriaBuilder(List<String> designations) {
29+
CriteriaQuery<DeptEmployee> criteriaQuery = createCriteriaQuery(DeptEmployee.class);
30+
Root<DeptEmployee> root = criteriaQuery.from(DeptEmployee.class);
31+
In<String> inClause = criteriaBuilder.in(root.get("designation"));
32+
for (String designaiton : designations) {
33+
inClause.value(designaiton);
34+
}
35+
criteriaQuery.select(root)
36+
.where(inClause);
37+
TypedQuery<DeptEmployee> query = entityManager.createQuery(criteriaQuery);
38+
return query.getResultList();
39+
}
40+
41+
@Override
42+
public List<DeptEmployee> filterbyDesignationUsingExpression(List<String> designations) {
43+
CriteriaQuery<DeptEmployee> criteriaQuery = createCriteriaQuery(DeptEmployee.class);
44+
Root<DeptEmployee> root = criteriaQuery.from(DeptEmployee.class);
45+
criteriaQuery.select(root)
46+
.where(root.get("designation")
47+
.in(designations));
48+
TypedQuery<DeptEmployee> query = entityManager.createQuery(criteriaQuery);
49+
return query.getResultList();
50+
}
51+
52+
@Override
53+
public List<DeptEmployee> searchByDepartmentQuery(String searchKey) {
54+
CriteriaQuery<DeptEmployee> criteriaQuery = createCriteriaQuery(DeptEmployee.class);
55+
Root<DeptEmployee> emp = criteriaQuery.from(DeptEmployee.class);
56+
57+
Subquery<Department> subquery = criteriaQuery.subquery(Department.class);
58+
Root<Department> dept = subquery.from(Department.class);
59+
subquery.select(dept)
60+
.distinct(true)
61+
.where(criteriaBuilder.like(dept.get("name"), new StringBuffer("%").append(searchKey)
62+
.append("%")
63+
.toString()));
64+
65+
criteriaQuery.select(emp)
66+
.where(criteriaBuilder.in(emp.get("department"))
67+
.value(subquery));
68+
69+
TypedQuery<DeptEmployee> query = entityManager.createQuery(criteriaQuery);
70+
return query.getResultList();
71+
}
72+
73+
private <T> CriteriaQuery<T> createCriteriaQuery(Class<T> klass) {
74+
return criteriaBuilder.createQuery(klass);
75+
}
76+
77+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
package com.baeldung.hibernate.jpacriteriabuilder;
2+
3+
import static org.hamcrest.MatcherAssert.assertThat;
4+
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
5+
import static org.junit.Assert.assertEquals;
6+
7+
import java.io.IOException;
8+
import java.util.ArrayList;
9+
import java.util.List;
10+
import java.util.stream.Collectors;
11+
12+
import javax.persistence.EntityManager;
13+
14+
import org.hibernate.HibernateException;
15+
import org.hibernate.Session;
16+
import org.junit.After;
17+
import org.junit.Before;
18+
import org.junit.Test;
19+
20+
import com.baeldung.hibernate.HibernateUtil;
21+
import com.baeldung.hibernate.entities.Department;
22+
import com.baeldung.hibernate.entities.DeptEmployee;
23+
import com.baeldung.hibernate.jpacriteriabuilder.service.EmployeeSearchService;
24+
import com.baeldung.hibernate.jpacriteriabuilder.service.EmployeeSearchServiceImpl;
25+
26+
public class EmployeeSearchServiceIntegrationTest {
27+
28+
private EntityManager entityManager;
29+
private EmployeeSearchService searchService;
30+
private Session session;
31+
32+
@Before
33+
public final void setup() throws HibernateException, IOException {
34+
session = HibernateUtil.getSessionFactory()
35+
.openSession();
36+
entityManager = session.getEntityManagerFactory()
37+
.createEntityManager();
38+
searchService = new EmployeeSearchServiceImpl(entityManager);
39+
40+
entityManager.getTransaction()
41+
.begin();
42+
Department department = new Department("Pre Sales");
43+
DeptEmployee employee = new DeptEmployee("John Smith", "001", "Manager", department);
44+
entityManager.persist(department);
45+
entityManager.persist(employee);
46+
employee = new DeptEmployee("Ian Evans", "002", "Associate", department);
47+
entityManager.persist(department);
48+
entityManager.persist(employee);
49+
department = new Department("Copporate Sales");
50+
employee = new DeptEmployee("Robert Carter", "003", "Manager", department);
51+
entityManager.persist(department);
52+
entityManager.persist(employee);
53+
employee = new DeptEmployee("John Carter", "004", "Senior Manager", department);
54+
entityManager.persist(employee);
55+
employee = new DeptEmployee("David Guetta", "009", "Associate", department);
56+
entityManager.persist(department);
57+
entityManager.persist(employee);
58+
department = new Department("Post Sales");
59+
employee = new DeptEmployee("Robert Jonas", "005", "Director", department);
60+
entityManager.persist(department);
61+
entityManager.persist(employee);
62+
employee = new DeptEmployee("John Ferros", "006", "Junior Associate", department);
63+
entityManager.persist(department);
64+
entityManager.persist(employee);
65+
department = new Department("Client Support");
66+
employee = new DeptEmployee("Robert Mcclements", "007", "Director", department);
67+
entityManager.persist(department);
68+
entityManager.persist(employee);
69+
employee = new DeptEmployee("Peter Parker", "008", "Manager", department);
70+
entityManager.persist(department);
71+
entityManager.persist(employee);
72+
73+
}
74+
75+
@After
76+
public final void teardown() {
77+
entityManager.getTransaction()
78+
.rollback();
79+
entityManager.close();
80+
}
81+
82+
@Test
83+
public final void givenCriteriaQuery_whenSearchedUsingCriteriaBuilderWithListofAuthors_thenResultIsFilteredByAuthorNames() {
84+
List<String> designations = new ArrayList<String>() {
85+
{
86+
add("Manager");
87+
add("Senior Manager");
88+
add("Director");
89+
}
90+
};
91+
List<DeptEmployee> result = searchService.filterbyDesignationUsingCriteriaBuilder(designations);
92+
assertEquals("Number of Employees does not match with expected.", 6, result.size());
93+
assertThat(result.stream()
94+
.map(DeptEmployee::getDesignation)
95+
.distinct()
96+
.collect(Collectors.toList()), containsInAnyOrder(designations.toArray()));
97+
}
98+
99+
@Test
100+
public final void givenCriteriaQuery_whenSearchedUsingExpressionWithListofAuthors_thenResultIsFilteredByAuthorNames() {
101+
List<String> designations = new ArrayList<String>() {
102+
{
103+
add("Manager");
104+
add("Senior Manager");
105+
add("Director");
106+
}
107+
};
108+
List<DeptEmployee> result = searchService.filterbyDesignationUsingExpression(designations);
109+
assertEquals("Number of Employees does not match with expected.", 6, result.size());
110+
assertThat(result.stream()
111+
.map(DeptEmployee::getDesignation)
112+
.distinct()
113+
.collect(Collectors.toList()), containsInAnyOrder(designations.toArray()));
114+
}
115+
116+
@Test
117+
public final void givenCriteriaQuery_whenSearchedDepartmentLike_thenResultIsFilteredByDepartment() {
118+
List<DeptEmployee> result = searchService.searchByDepartmentQuery("Sales");
119+
assertEquals("Number of Employees does not match with expected.", 7, result.size());
120+
// assertThat(result.stream().map(DeptEmployee::getDesignation).distinct().collect(Collectors.toList()), containsInAnyOrder(designations.toArray()));
121+
}
122+
}

0 commit comments

Comments
 (0)