【发布时间】:2021-05-06 15:00:45
【问题描述】:
在我的 Java 代码中,我有一个 JPA 实体定义如下
public class Entity {
@Id
private Long id;
... other attributes;
@Column(name = "ctx")
@Convert(converter = MapToJsonStringConverter.class)
private Map<String, String> ctx;
}
@Convert
public class MapToJsonStringConverter implements AttributeConverter<Map<String, String>, String> {
@Autowired
private JsonParserService jsonParserService;
@Override
public String convertToDatabaseColumn(final Map<String, String> map) {
return Optional.ofNullable(map)
.map(jsonParserService::writeValueAsString)
.orElse(null);
}
@Override
public Map<String, String> convertToEntityAttribute(final String string) {
return Optional.ofNullable(string)
.map(jsonParserService::readValueAsMap)
.orElse(null);
}
}
Jpa 属性转换器用于将ctx 属性与 JSON 字符串转换。我需要创建一个 JPA 规范,允许我使用 LIKE 子句查询数据库中的 ctx 字段:
ctx LIKE '%test-value%'
当然,当我尝试创建这样的规范时,标准构建器无法匹配属性的类型,因为它需要一个映射,而我只提供一个字符串
cb.like(root.get(Entity_.ctx), string)) <--- compile error Cannot resolve method 'like(javax.persistence.criteria.Expression<M>, java.lang.String)'
有没有办法让这项工作而不是使用本机查询?考虑到最终规范还涉及同一实体的其他属性。
【问题讨论】:
-
ctx是String。可以提供MapToJsonStringConverter吗? -
更新原帖
-
请提供
ctx的例子 -
它是一个包含键值属性的 json 映射的字符串 ->
{ "key": "value", "anotherKey": "anotherValue"} -
你试过
cb.like(root.get(Entity_.ctx).as(String.class), string)吗?提到here