Milkmaid Milkmaid - 7 months ago 15
Java Question

How to check in JPA if joined column contains data with condition

I have two tables.

Person and his vacation plannings. For this question everything we need to know is that Person contains Id and vp contains this id as a foreign key, and year and start date end date. Person can contains more vp.
thus

Person VacPlan
_______ ____________
|id |----->|pers_id |
|year |
|start date |
|end date |


I need to select every person who don't have a single record in vp for specified year.

Something like:
select from person where (joined vp where vp.year = :year) is not empty


Do you have any ideas how to make this in JPA(eclipse link)

EDIT:
this is how criteria looks like

List<Predicate> predicates = new ArrayList<>();
List<Predicate> subPredicates = new ArrayList<>();
CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaQuery<PersonVP> q = cb.createQuery(PersonVP.class);
Root<PersonVP> person = q.from(PersonVP.class);

Subquery<VacationPlanning> subquery = q.subquery(VacationPlanning.class);
Root<VacationPlanning> subRoot = subquery.from(VacationPlanning.class);

Expression<String> exp = person.get("personnelNumber");
subPredicates.add(cb.equal(subRoot.get("year"), year));
subPredicates.add(cb.equal(exp, subRoot.get("perNr")));
subquery.where(cb.and(subPredicates.toArray(new Predicate[subPredicates.size()])));

if (STATUS.FILLED.equals(searchFillStatus)) {
predicates.add(cb.and(cb.exists(subquery)));
} else if (STATUS.NOT_FILLED.equals(searchFillStatus)) {
predicates.add(cb.and(cb.not(cb.exists(subquery))));
}

q.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));

q.select(person);
TypedQuery<PersonVP> query = getEntityManager().createQuery(q);

return query.setFirstResult(from)
.setMaxResults(to)
.getResultList();

Answer

Something like this should work:

select p from Person p where not exists(
    select vp.id from Person p2 
    join p2.vacPlans vp
    where p2.id = p.id
    and vp.year = :year)
Comments