Assume the following query:
public List<UserEntity> search(String str, Integer page, Integer limit) {
String sql = "SELECT u FROM UserEntity u ";
if (str.length() > 0) {
sql = "INNER JOIN u.account a ";
}
sql = "WHERE 1 = 1 ";
if (str.length() > 0) {
sql = "AND LOWER(u.name) LIKE :str OR LOWER(u.surname) LIKE :str OR LOWER(a.email) LIKE :str ";
}
Query q = entityManager.createQuery(sql);
if (str.length() > 0) {
q.setParameter("str", str.toLowerCase() "%");
}
q.setFirstResult(page * limit);
q.setMaxResults(limit);
return q.getResultList();
}
As you can see, we have two conditions which will determine if the table will be joined with another one and if there will be some where conditions. Furthermore, we have OR conditions so that the input "str" can be checked against multiple columns (one of which taken from the joined account table).
Now I would like to write this up using CriteriaQuery, but the problem is I cannot manage to include all the conditions above.
CodePudding user response:
Finally came up with a really good solution. This is how!
public List<UserEntity> search(String str, Integer page, Integer limit) {
CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<UserEntity> query = qb.createQuery(UserEntity.class);
Root<UserEntity> root = query.from(UserEntity.class);
query.select(root);
if (str.length() > 0) {
Predicate checkName = qb.equal(root.get("name"), str);
Predicate checkSurname = qb.equal(root.get("surname"), str);
Predicate checkEmail = qb.equal(root.get("account").get("email"), str);
query.where(
qb.or( checkName, checkSurname, checkEmail)
);
}
Query q = entityManager.createQuery(query);
q.setFirstResult(page * limit);
q.setMaxResults(limit);
return q.getResultList();
}
