Search code examples
javahibernatequerydsl

With QueryDSL, how do you create an expression on a collection where the sub-items match all criteria?


Assume I have an Appointment table and a Person table, where an Appointment has many Persons.

If I wanted to find all Appointments containing at least one Person in my list I would do:

Collection<Person> personsList = getInterestedPersons();
BooleanExpresssion expr = appointment.persons.any().in(personsList)

However, what I really want to so is find all Appointments that have ALL the persons in my list.

So, how can I construct a BooleanExpression that will let me filter for all Appointments who have all the Persons?

Note: I must create a BooleanExprsesion, because this is part of a larger generic filter for Appointments, where all the BooleanExpressions get and()ed together.

Another note, I do not what to find Appointments that have only those Persons, just at least all those in the list.


Solution

  • In this case, I guess the following should work:

    BooleanBuilder personClause = new BooleanBuilder();
    for (Person person : personList)
    {
        personClause.and(appointment.persons.contains(person));
    }
    query.where(personClause); // to add the clause