简体   繁体   中英

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}]?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM