假设我查询一个列中包含原始 json
的表,或者我自己用这样的子查询创建 json:
select
p.name,
(select json_build_array(json_build_object('num', a.num, 'city', a.city)) from address a where a.id = p.addr) as addr
from person p;
如何指示 Spring 的 NamedParameterJdbcTemplate
不转义
addr
列但不管它吗?
到目前为止,它坚持返回给我这样的东西:
[{
name: "John",
addr: {
type: "json",
value: "{"num" : "123", "city" : "Luxembourg"}"
}
}]
最佳答案
这是可行的解决方案。
服务:
@Transactional(readOnly = true)
public String getRawJson() {
String sql = "select json_agg(row_to_json(json)) from ( "
+ "select "
+ "p.id, "
+ "p.name, "
+ "(select array_to_json(array_agg(row_to_json(c))) from ( "
+ " ... some subselect ... "
+ ") c ) as subq "
+ "from person p "
+ "where type = :type "
+ ") json";
MapSqlParameterSource params = new MapSqlParameterSource("type", 1);
return jdbcTemplate.queryForObject(sql, params, String.class);
}
Controller :
@ResponseBody
@GetMapping(value = "/json", produces = MediaType.APPLICATION_JSON_VALUE)
public String getRawJson() {
return miscService.getRawJson();
}
关键是 json_agg
和 row_to_json/array_to_json
的组合加上返回 String
以避免任何类型转换。
关于sql - jdbcTemplate 和原始 JSON 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52709687/