简体   繁体   English

使用 CriteriaQuery 进行复杂查询

[英]Using CriteriaQuery for complex queries

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.如您所见,我们有两个条件将确定表是否将与另一个表连接,以及是否会有一些 where 条件。 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).此外,我们有 OR 条件,以便可以针对多个列(其中一个取自连接帐户表)检查输入“str”。

Now I would like to write this up using CriteriaQuery, but the problem is I cannot manage to include all the conditions above.现在我想使用 CriteriaQuery 来编写它,但问题是我无法设法包含上述所有条件。

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(); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM