【发布时间】:2023-04-07 13:46:02
【问题描述】:
最好在 Java 方面使用 Jackson。我已经尝试了明显的解决方案:
public class JsonObjectConverter implements Converter<Object, ObjectNode> {
private final ObjectMapper mapper = new ObjectMapper();
@Override public ObjectNode from(Object dbo) {
try {
return dbo != null ? mapper.readValue((String) dbo, ObjectNode.class) : null;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override public Object to(ObjectNode uo) {
try {
return uo != null ? mapper.writeValueAsString(uo) : null;
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
@Override public Class<Object> fromType() {
return Object.class;
}
@Override public Class<ObjectNode> toType() {
return ObjectNode.class;
}
}
但如果我尝试使用它,我会收到如下错误:
org.jooq.exception.DataAccessException: SQL [insert into "public"."my_table" ("id", "stuff") values (?, ?)]; ERROR: column "stuff" is of type json but expression is of type character varying
Hint: You will need to rewrite or cast the expression.
但是由于 jOOQs 强制类型安全(这很好,顺便说一句),我不能只添加一个 .cast(String.class) 就完成了。那么,我需要在转换器中做其他事情,还是应该以不同的方式调用代码?我目前正在这样做:
Long id = ...
ObjectNode stuff = ...
create.insertInto(MY_TABLE)
.set(MY_TABLE.ID, id)
.set(MY_TABLE.STUFF, stuff)
.execute();
并且在我的代码的其他地方使用可更新记录。
【问题讨论】:
标签: java sql postgresql jooq