现有A,B,C,D四个字段,A,B字段需要判断是否为空值,如果为空则不参与条件查询,D字段为String,但对应数据库字段为LoaclDate,现在要将A,B,C字段精确匹配,D字段模糊匹配,用JPA原生查询应该怎么写
时间: 2024-03-17 13:43:36 浏览: 21
可以使用 JPA 的 CriteriaQuery 来实现该查询,具体代码如下:
```java
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Entity> cq = cb.createQuery(Entity.class);
Root<Entity> root = cq.from(Entity.class);
// 构造 A,B 字段的判断条件
Predicate predicate = cb.conjunction();
if (StringUtils.isNotBlank(a)) {
predicate = cb.and(predicate, cb.equal(root.get("a"), a));
}
if (StringUtils.isNotBlank(b)) {
predicate = cb.and(predicate, cb.equal(root.get("b"), b));
}
// 构造 C 字段的精确匹配条件
if (StringUtils.isNotBlank(c)) {
predicate = cb.and(predicate, cb.equal(root.get("c"), c));
}
// 构造 D 字段的模糊匹配条件
if (StringUtils.isNotBlank(d)) {
predicate = cb.and(predicate, cb.like(root.get("d").as(String.class), "%" + d + "%"));
}
cq.where(predicate);
TypedQuery<Entity> query = entityManager.createQuery(cq);
List<Entity> result = query.getResultList();
```
其中,`EntityManager` 是 JPA 中的实体管理器,`Entity` 是实体类,`StringUtils` 是 Apache Commons Lang 库中的字符串工具类,用于判断字符串是否为空或空白字符。以上代码中,`cb.conjunction()` 表示构造一个空的并集条件,`cb.equal()` 表示构造等值条件,`cb.like()` 表示构造模糊匹配条件,`root.get()` 表示获取实体类中的属性,`cq.where()` 表示设置查询条件,`entityManager.createQuery()` 表示构造 JPA 查询对象,`query.getResultList()` 表示执行查询并返回结果列表。
相关推荐
![tbx](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)