【发布时间】:2021-12-11 13:32:18
【问题描述】:
我正在尝试使用带有过滤器的条件查询从表 MyEntity 中获取行数。
这个过滤器(函数参数)是一个JsonNode,键(JsonNode过滤器)作为实体中的列,值(JsonNode过滤器)可以是String或JsonNode类型,具体取决于用户传递的过滤器。
例如。
如果过滤器是{"policy": {"id": "123"}},则搜索具有json类型{"id": "123"}值的列policy,
如果过滤器是{"string_column": "test_string"},则搜索列string_column,其值为字符串类型test_string。
使用的数据库是 PostgreSQL。
这是我的代码 -
public Long getCountForMyEntity(JsonNode filter) {
CriteriaBuilder criteriaBuilder = sessionFactory.getCriteriaBuilder();
CriteriaQuery<Long> query = criteriaBuilder.createQuery(Long.class);
Root<MyEntity> root = query.from(MyEntity.class);
query.select(criteriaBuilder.count(root));
Iterator<Map.Entry<String, JsonNode>> filterFields = filter.fields();
while(filterFields.hasNext()) {
Map.Entry<String, JsonNode> field = filterFields.next();
String fieldName = field.getKey();
JsonNode fieldValue = field.getValue();
Object value = fieldValue;
System.out.println(fieldValue + " : " + fieldValue.getNodeType());
if (fieldValue.getNodeType() == JsonNodeType.STRING) {
value = fieldValue.asText();
}
query.where(criteriaBuilder.equal(root.get(fieldName), value));
}
return sessionFactory.getCurrentSession().createQuery(query).getSingleResult();
}
这适用于当过滤器值为字符串但过滤器值为 json 时获取计数,我收到以下错误 -
44- [WARN ] 2021-10-26 14:42:35 [http-nio-9090-exec-7] o.h.e.j.s.SqlExceptionHelper [][][][] - SQL Error: 0, SQLState: 42883
45- [ERROR] 2021-10-26 14:42:35 [http-nio-9090-exec-7] o.h.e.j.s.SqlExceptionHelper [][][][] - ERROR: operator does not exist: json = unknown
Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.
Position: 121
46- [WARN ] 2021-10-26 14:42:35 [http-nio-9090-exec-7] o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver [][][][] - Resolved [org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet]
我尝试过像这样直接传递fieldValue,但仍然是同样的错误-
query.where(criteriaBuilder.equal(root.get(fieldName), fieldValue));
知道我哪里出错了吗?有没有过滤json/非字符串值的好方法?
【问题讨论】:
标签: java spring hibernate criteria hibernate-criteria