一个客户拥有多个订单
1 <resultMap type="User" id="UserOrderResultMap"> 2 <id column="id" property="id"/> 3 <result column="name" property="name"/> 4 5 <!-- 如何体现出User中封装的订单呢?需要用到collection标签 --> 6 <!-- 7 collection:需要封装的集合 8 property:关联属性的名字 9 --> 10 <!-- <collection property="orders" javaType="Order"> --> 11 <!-- opType使用alt+/会自动提示 --> 12 <collection property="orders" ofType="Order"> 13 <id column="order_id" property="id"/> 14 <result column="orderno" property="orderno"/> 15 <result column="productname" property="productname"/> 16 </collection> 17 18 </resultMap> 19 20 <select id="queryUserOrder" resultMap="UserOrderResultMap"> 21 SELECT u.id,u.name,o.orderno,o.id order_id,o.productname FROM t_user u LEFT JOIN t_order o ON o.user_id=u.id 22 </select>
User.java:
1 package cn.sm1234.domain; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 public class User { 7 8 private Integer id; 9 private String name; 10 private String password; 11 12 private List<Order> orders = new ArrayList<Order>(); 13 14 public Integer getId() { 15 return id; 16 } 17 public void setId(Integer id) { 18 this.id = id; 19 } 20 public String getName() { 21 return name; 22 } 23 public void setName(String name) { 24 this.name = name; 25 } 26 public String getPassword() { 27 return password; 28 } 29 public void setPassword(String password) { 30 this.password = password; 31 } 32 public List<Order> getOrders() { 33 return orders; 34 } 35 public void setOrders(List<Order> orders) { 36 this.orders = orders; 37 } 38 39 40 }
1 package cn.sm1234.dao; 2 3 import java.util.List; 4 5 import cn.sm1234.domain.User; 6 7 public interface UserDao { 8 9 public List<User> queryUserOrder(); 10 }
1 @Test 2 public void test3() { 3 SqlSession sqlSession = SessionUtils.getSession(); 4 // getMapper(): 返回指定接口的动态代理的实现类对象 5 UserDao dao = sqlSession.getMapper(UserDao.class); 6 List<User> userList = dao.queryUserOrder(); 7 for (User user : userList) { 8 System.out.println("用户信息"+user.getId()+"-"+user.getName()); 9 for(Order order : user.getOrders()){ 10 System.out.println("订单信息"+order.getOrderno()+"-"+order.getProductname()); 11 } 12 } 13 sqlSession.commit(); 14 sqlSession.close(); 15 }
数据库信息:
测试查询结果: