Here is an example how to add where()
clause:
public static <T> List<T> findEntity(Class<T> entityClass, boolean isEnabled) {
CriteriaQuery<T> criteria = builder.createQuery(entityClass);
Root<T> entityRoot = criteria.from(entityClass);
criteria.select(entityRoot);
criteria.where(builder.equal(
entityRoot.get("enable"), //path expression
builder.parameter(Boolean.class, "isEnabled")) //parameter expression
);
criteria.orderBy(order);
return em.createQuery(criteria)
.setParameter("isEnabled", isEnabled)
.getResultList();
}
The entityRoot.get("enable")
statement defines Path<String>
expression. This is equivalent of a.enable
which uses a colon to denote a parameter in JPQL, i.e.
SELECT a FROM Activity a WHERE a.enable = :isEnabled
To build conditional expression one must also create a ParameterExpression<Boolean>
which corresponds to the parameter of typed query that executes our criteria.
Using this approach you can easily extend your generic method with new parameters.
I hope it helps.