Reputation: 5587
I have the following Criteria API query used to evaluate a given value against a number of Subject
attributes.
...
Expression literal = builder.literal((String) "%" + filterValue + "%");
// When the globalFilter is deleted it returns ""
if (!"".equals(filterValue)) {
// JPQL equivilant: SELECT e FROM Subject e JOIN e.company c JOIN e.contact ct WHERE c.name LIKE :literal OR ct.firstName LIKE :literal ... etc
List<Predicate> globalPredicate = new ArrayList<>();
globalPredicate.add(builder.like(subject.get(Subject_.email), literal));
globalPredicate.add(builder.like(subject.join(Subject_.contact).get(Contact_.firstName), literal));
globalPredicate.add(builder.like(subject.join(Subject_.contact).get(Contact_.lastName), literal));
globalPredicate.add(builder.like(subject.join(Subject_.metier).get(Metier_.name), literal));
globalPredicate.add(builder.like(subject.join(Subject_.company).get(Company_.name), literal));
predicates.add(builder.or(globalPredicate.toArray(new Predicate[globalPredicate.size()])));
}
...
This creates the following query:
SELECT t1.UID AS a1, t1.EMAIL AS a2, t1.PASSWORD AS a3, t1.VERSION AS a4, t1.COMPANY_ID AS a5, t1.METIER_ID AS a6, t1.ACCOUNT_ID AS a7, t1.CONTACT_ID AS a8 FROM METIER t3, COMPANY t2, SUBJECT t1, CONTACT t0 WHERE (((((t1.EMAIL LIKE ? OR t0.FIRSTNAME LIKE ?) OR t0.LASTNAME LIKE ?) OR t3.NAME LIKE ?) OR (t2.NAME LIKE ? IS NOT NULL)) AND (((t0.ID = t1.CONTACT_ID) AND (t3.ID = t1.METIER_ID)) AND (t2.ID = t1.COMPANY_ID))) LIMIT ?, ?
The problem I am having is that the Subject_.company
can be null
. The query effectively ignores ALL the entries that have Subject_.company
set to null
.
I need to somehow modify this query so that the null
values are not automatically discarded.
Upvotes: 0
Views: 194
Reputation: 21145
You need to use the join method that takes a JoinType parameter, and specify JoinType.LEFT so that it uses a left outer join instead of the default.
globalPredicate.add(builder.like(subject.join(Subject_.company, JoinType.LEFT).get(Company_.name), literal));
A left outer join will prevent the Subject->Company relation from filtering out results with null companies.
Upvotes: 2