JDBCTemplate RowMapper 读取 postgres 表中的 jsonb 列
Posted
技术标签:
【中文标题】JDBCTemplate RowMapper 读取 postgres 表中的 jsonb 列【英文标题】:JDBCTempalte RowMapper to read jsonb column in postgres table 【发布时间】:2020-10-30 00:17:22 【问题描述】:我正在使用 JDBCTemplate 读取 Postgres 表,该表具有以下架构:
orderid|order_name|features|extra_features|
orderid:整数 订单名称:文本 特点:josnb 额外功能:jsonb
订购 DTO:
public class Order
private Integer orderid;
private String orderName;
List<Features> features;
List<ExtraFeatures> extraFeatures;
....
getter & setter
功能 DTO:
public class Features
private String featureName:
private String featureValuel
现在,在执行 SELECT * FROM public.orders 查询时,我正在编写如下所示的 rowMapper:
jdbcTemplate.query("SELECT * FROM public.orders", new OrderRowMapper())
行映射器
public class OrderRowMapper implements RowMapper<Order>
@Override
public Order mapRow(ResultSet rs, int rowNum) throws SQLException
Order order = new Order();
order.setOrderid(rs.getInt("orderid"));
order.setFeatures()// how to read jsonbcolumn?
我可以设置除 jsonb 列之外的所有值,我不知道如何为此实现 RowMapper,请帮助。
【问题讨论】:
你试过ObjectMapper mapper = new ObjectMapper(); List<Features> features = objectMapper.readValue(rs.getString("features"), new TypeReference<List< Features >>());
您的解决方案正在运行。 (Y)
ObjectMapper
是线程安全的,所以你可以引用它
【参考方案1】:
public class OrderRowMapper implements RowMapper<Order>
private ObjectMapper mapper = new ObjectMapper();
@Override
public Order mapRow(ResultSet rs, int rowNum) throws SQLException
List<Features> features = objectMapper
.readValue(rs.getString("features"),
new TypeReference<List<Features>>());
Order order = new Order();
order.setOrderid(rs.getInt("orderid"));
order.setFeatures()// how to read jsonbcolumn?
【讨论】:
以上是关于JDBCTemplate RowMapper 读取 postgres 表中的 jsonb 列的主要内容,如果未能解决你的问题,请参考以下文章
Spring中JdbcTemplate中使用RowMapper
Springboot使用JdbcTemplate RowMapper查询,直接返回实体列表