我正在尝试在ParameterizedRowMapper中设置父列表,如何编写或接近它。我有两个对象,一个用于父级,一个用于子级,但子级包含List。每个子级的父级存储在数据库中的单独表中,映射为1 - 多个。
父项记录的选择将在单独的ResultSet中完成。是否必须单独完成映射(单独的ParameterizedRowMapper ),如果是这样,我将如何编写 ParameterizedRowMapper 这是主要关注 ParameterizedRowMapper 是为了容纳列表项而编写的。
了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;
}
}
根据我的研究,我发现我需要使用 ResultSetExtractor ,但是我对使用它有疑问。在设置父级时,我是否将它集成到课程中?有人可以指导我如何以正确的方式完成
Children.java
Public class Children(){
int cid;
String firstName;
String lastName;
List<Parent>parents;
..
//getters/setters
}
Parent.java
Public class Parent(){
int pid;
String firstName;
String lastName;
..
//setters/getters
}
答案 0 :(得分:1)
我将展示如何为规范的1对多示例执行此操作,您可以将其调整为您的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
}
为每个类使用两个rowmappers,然后使用结果集提取器将多行转换为一个订单+订单项
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;
}
});
}