简体   繁体   中英

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

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)

Give this a try:

SELECT p.id 
FROM person p 
WHERE p.id NOT IN (SELECT DISTINCT(vp.pers_id)
              FROM VacPlan vp)

You can use NamedQuery for this job. You declare a NamedQuery using @JB Nizet query inside your Person Entity file like that :

@NamedQuery(name="VpForYear", query="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)")

And you can use this NamedQuery like that :

Query query = em.createNamedQuery("VpForYear");
query.setParameter("year", 2016);

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