Karthik Suresh
Karthik Suresh

Reputation: 407

Hibernate 5, Criteria Query for where clause with 2 restrictions

For an Employee Table

public class Employee {
    
    private Long id;
    
    private int deptId;
    
    private String name;
    
    private LocalDateTime joiningDate;
    
    private LocalDateTime seperatedDate;

}

I want build a criteria with both of the below condition

criteriaQuery.where((EmployeeRoot.get("deptId").in(request.getDeptIdList())));
criteriaBuilder.greaterThanOrEqualTo(EmployeeRoot.get("joiningDate"), startDate)); 

But it only takes the latest Predicate. How can i combine both like [Where {condition1} + AND {condition2}] ?

Upvotes: 2

Views: 1448

Answers (1)

SternK
SternK

Reputation: 13111

You should do something like this:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Employee> criteria = builder.createQuery(Employee.class);
Root<Employee> root = criteria.from(Employee.class);
criteria
  .select(...)
  .where(
      builder.and(
         root.get("deptId").in(request.getDeptIdList()),
         builder.greaterThanOrEqualTo(root.get("joiningDate"), startDate))
      )
  );
entityManager.createQuery(criteria).getResultList();

Upvotes: 4

Related Questions