Reputation: 785
Is it possible to ignore cb.equal(myClass.get(MyClass_.token), token)
if token
is null without duplicating query? I do not want to pack it into huge if that completely duplicates the query (with just skipping one condition).
private MyClass find(String code, String token) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<MyClass> cq = cb.createQuery(MyClass.class);
Root<MyClass> myClass = cq.from(MyClass.class);
cq.select(myClass).where(
cb.and(cb.equal(myClass.get(MyClass_.code), code),
cb.equal(myClass.get(MyClass_.token), token),
cb.greaterThan(myClass.get(MyClass_.expirationDate), DateUtils.getTime())
));
....
}
Upvotes: 1
Views: 849
Reputation: 879
Do Something like below. Note I just text edited your code and didnt actually check for syntax errors or compile it
private MyClass find(String code, String token) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<MyClass> cq = cb.createQuery(MyClass.class);
Root<MyClass> myClass = cq.from(MyClass.class);
Predicate predicate = cb.and(
cb.equal(myClass.get(MyClass_.code), code),
cb.greaterThan(myClass.get(MyClass_.expirationDate), DateUtils.getTime())
);
if (token != null)
predicate = cb.and(predicate, cb.equal(myClass.get(MyClass_.token), token));
cq.select(myClass).where(predicate);
}
Upvotes: 1