I want to know how to use JPA Criteria API to filter entity by related entity's foreign key.
Let's say i have two entities as the following:
public class Employee {
@Id
private Long id;
...
@ManyToOne
private Department department;
...
}
public class Department {
@Id
private Long id;
}
I want to query the employees under departments of ids (1,2,3).
I was able to do that using Hibernate's depricated criteria, And want to know how to do it using the JPA Criteria predicate without join (root.join). It is logical that i don't need any join or subquery, as the desired result can be fetched from one table:
select e.* from employee e where e.department_id in (1,2,3)
** Update **
My problem was - as new for JPA Criteria and coming from the deprecated Hibernate Criteria - that I've used all APIs from the CriteriaBuilder such as (equal, notEqual, isNull, like, .....); And ,thus , used the CriteriaBuilder.In(experssion).in(values)
.
But, as shown in the answer of @frank, I figured out that for the IN usage, I'll use Root.get(<attr>).in(<values>)
The CriteriaBuilder.in
also can be used but differently:
In<Object> inClause = criteriaBuilder.in(root.get(<attr>);
for (Long id : ids) {
inClause.value(id);
}
But, Of-course, the first solution is easier.