[使用rowMapper将jsonb列映射到Java模型
来源:爱站网时间:2021-09-16编辑:网友分享
我的数据库表中有一些jsonb列。我正在使用PostgreSQL例如CREATE TABLE交易(id serial NOT NULL,帐户jsonb,// .. // ..);我需要将这些jsonb列映射到我的数据...
问题描述
我的数据库表有几jsonb
列。我正在使用PostgreSQL例如
CREATE TABLE trades (
id serial NOT NULL,
accounts jsonb,
//..
//..
);
我需要使用Springjsonb
RowMapper
将这些mapRow()
列映射到我的数据模型:
public class DataModelRowMapper implements RowMapper {
@Override
public TestModel mapRow(final ResultSet rs,
final int rowNum) throws SQLException {
List accounts = jsonParser.parse(rs.getString("accounts"), new TypeReference>() {
});
//other jsonb columns
Account account = accounts.stream()
.filter(account -> account.getType() == Type.CLIENT)
.findFirst()
.orElse(new Account());
final TestModel testModel = new TestModel();
testModel.setId(rs.getString("id"));
testModel.setAccountName(account.getName());
return testModel;
}
}
在mapRow()
内部,我将json解析为Java List
,然后通过流查找适当的值,因为返回了多个accounts
。我还有一些其他的jsonb列,我将在mapRow()
中进行类似的操作。
[以前,我是从SQL查询本身返回准确的值,事实证明这很慢,然后将此过滤逻辑移到Java代码的mapRow()
内部,目的是提高性能并返回结果。
我的问题是,我应该在mapRow内部解析和过滤逻辑吗?是否有更好的更快方法来加载jsonb
数据并映射到TestModel
accountName
字符串属性?
我的问题是,SQL查询在db上快速运行
思路:
如果您查看整个系统,则可能根本不需要解析这些字段。例如,在大多数情况下,需要返回不做任何修改的JSON。只需返回字符串。无需来回解析,这确实更快。
示例春季MVC:
@RequestMapping(value = "/getAll", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody
void getAll(HttpServletResponse response, @RequestBody final Entity request) throws IOException {
List res = null;
try {
List regList = entityDAO.getAll(request);
res = regList.stream().map(h -> h.getJson_obj()).collect(Collectors.toList()); // just collect
// res = regList.stream().map(h -> h.getJson_obj().replaceFirst("\\{", "{ \"vehicle_num\":" + h.getVehicle_num() + ",")).collect(Collectors.toList()); //it is also possible to add dynamic data without parsing
} catch (Exception e) {
logger.error("getAll ", e);
}
String resStr = "[" + res.stream().filter(t -> t != null).collect(Collectors.joining(", ")) + "]";
response.setHeader("Content-Type", "application/json;charset=UTF-8");
response.setStatus(200);
response.getWriter().println(resStr);
}
对不起,我不能发表评论,所以答案。