将对象列表映射到对象的ParameterizedRowMapper
我试图在ParameterizedRowMapper中设置父级列表,这是如何编写或处理的。我有两个对象,一个用于父对象,一个用于子对象,但是子对象包含一个List。每个子对象的父对象存储在数据库的单独表中,并且映射为1-许多。
父母记录的选择将在单独的ResultSet中完成。映射是否必须单独完成( 单独的ParameterizedRowMapper
),如果是这样,我将如何编写 这是如何编写
来容纳列表项的主要问题。
public static class ChildrenMapper implements ParameterizedRowMapper<Children>{ public Children mapRow(ResultSet rs, int rowNum) throws SQLException {
Children child = new Children();
child.setFirstName(rs.getString("firstName"));
child.setLastName(rs.getString("lastName"));
//a child can have many Parents or gaurdians
child.setParent(List<Parent>);
return child;
}
}
根据我的研究,我发现我需要使用
,但是我对此有疑问。在设置父级时,我是否将其集成到班级中?有人可以指导我如何正确地完成它
Public class Children(){int cid;
String firstName;
String lastName;
List<Parent>parents;
..
//getters/setters
}
Public class Parent(){ int pid;
String firstName;
String lastName;
..
//setters/getters
}
回答:
我将针对一个典型的一对多示例展示如何执行此操作,您可以将其调整为适合您的vo类/表。
订单类别
public class Order { private Long orderId;
private String user;
private List<LineItem> items;
// Getter / setter omitted
}
物品类别
public class LineItem { private Long lineItemId;
private String product;
private int quantity;
// Getter / setter omitted
}
每个类使用两个行映射器,然后使用结果集提取器将多行转换为一个顺序+订单项
OrderRepository
public final static RowMapper<Order> orderMapper = ParameterizedBeanPropertyRowMapper.newInstance(Order.class);public final static RowMapper<LineItem> lineItemMapper = ParameterizedBeanPropertyRowMapper.newInstance(LineItem.class);
public Order findOrderWithItems(Long orderId) {
return jdbcTemplate.query("select * from orders, line_item "
+ " where orders.order_id = line_item.order_id and orders.order_id = ?",
new ResultSetExtractor<Order>() {
public Order extractData(ResultSet rs) throws SQLException, DataAccessException {
Order order = null;
int row = 0;
while (rs.next()) {
if (order == null) {
order = orderMapper.mapRow(rs, row);
}
order.addItem(lineItemMapper.mapRow(rs, row));
row++;
}
return order;
}
}, orderId);
}
public List<Order> findAllOrderWithItmes() {
return jdbcTemplate.query("select * from orders, line_item "
+ " where orders.order_id = line_item.order_id order by orders.order_id",
new ResultSetExtractor<List<Order>>() {
public List<Order> extractData(ResultSet rs) throws SQLException, DataAccessException {
List<Order> orders = new ArrayList<Order>();
Long orderId = null;
Order currentOrder = null;
int orderIdx = 0;
int itemIdx = 0;
while (rs.next()) {
// first row or when order changes
if (currentOrder == null || !orderId.equals(rs.getLong("order_id"))) {
orderId = rs.getLong("order_id");
currentOrder = orderMapper.mapRow(rs, orderIdx++);
itemIdx = 0;
orders.add(currentOrder);
}
currentOrder.addItem(lineItemMapper.mapRow(rs, itemIdx++));
}
return orders;
}
});
}
以上是 将对象列表映射到对象的ParameterizedRowMapper 的全部内容, 来源链接: utcz.com/qa/414702.html