假设我查询一列中包含原始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"}"
}
}]
答案 0 :(得分:0)
这是有效的解决方案。
服务:
@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);
}
控制器:
@ResponseBody
@GetMapping(value = "/json", produces = MediaType.APPLICATION_JSON_VALUE)
public String getRawJson() {
return miscService.getRawJson();
}
键是json_agg
和row_to_json / array_to_json
的组合,加上返回String
以避免任何类型转换。