若返回值是对象,则使用MapHandler,如果返回的是集合,则使用MapListHandler
例子:此处有购物车,购物车中有商品id与商品对象属性
public List<Cart> selectCarts(long uid) {
//在查询时,使用关联表查询,可以直接将商品对象注入到购物车
String sql = "select * from cart c inner join product p on c.p_id=p.p_id where c.u_id=?";
try {
List<Map<String, Object>> list = runner.query(sql, new MapListHandler(), uid);
if(list != null){
List<Cart> carts = new ArrayList<>();
for(Map<String, Object> map : list){
//将map值注入到Cart对象,及product对象中,cart对象包含product对象
Cart cart = new Cart();
Product product = new Product();
BeanUtils.populate(cart,map);
BeanUtils.populate(product,map);
cart.setProduct(product);
carts.add(cart);
}
return carts;
}
} catch (SQLException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
以上代码根据购物车的id查找到购物车与商品信息,并注入Cart对象与product对象中,在此处,使用MapListHandler,处理关联查询结果的对象。(使用BeanUtils.populate注入)
浙公网安备 33010602011771号