查询所有客户以及对应的订单
目录
左连接查询(不支持懒加载)
场景:我们想要查询出所有的客户,并且把每个客户对应的订单也查出来。这时候可以使用左连接查询。
那么如何在 MyBatis 中实现左连接查询呢?
给客户的 domain 增添一个字段来表示对应的订单:private List<Order> orders = new ArrayList<>();
@Setter
@Getter //使用注解生成 get 与 set 方法
@ToString
public class Customer {
private Integer cust_id;
private String cust_name;
private String cust_profession;
private String cust_phone;
private String email;
private List<Order> orders = new ArrayList<>(); // 对应的订单
}
在 CustomerMapper 接口类中添加方法:
/*查询客户和订单*/
public List<Customer> getAllCustomer();
在 CustomerMapper 映射文件中写 SQL:由于查询结果既包含客户又包含订单,我们需要用 resultMap 来自定义结果集。
与之前查询订单(多)附带客户(一)的 association 相对于,这里查询客户(一)附带订单(多)需要 collection 标签。
代码如下:
<!--自定义结果集-->
<resultMap id="custMap" type="customer">
<id column="cust_id" property="cust_id"/>
<result column="cust_name" property="cust_name"/>
<result column="cust_phone" property="cust_phone"/>
<result column="cust_profession" property="cust_profession"/>
<result column="email" property="email"/>
<collection property="orders" ofType="Order">
<id column="order_id" property="order_id"/>
<result column="order_name" property="order_name"/>
<result column="order_num" property="order_num"/>
</collection>
</resultMap>
<!--查询所有客户和订单-->
<select id="getAllCustomer" resultMap="custMap"> /*使用自定义的结果集*/
SELECT * FROM `customer` AS c LEFT JOIN `order` AS o ON c.cust_id = o.cust_id;
</select>
测试类中:
public void test4(){
SqlSession sqlSession = MybatisUtils.openSession();
CustomerMapper customerMapper = sqlSession.getMapper(CustomerMapper.class);
List<Customer> allCustomer = customerMapper.getAllCustomer();
for (Customer customer : allCustomer) {
System.out.println(customer);
}
sqlSession.close();
}
运行结果:成功查询出所有的客户与他们对应的订单。
分步查询(支持懒加载)
分步查询也可以达到我们的要求,先查出所有客户的信息,再根据查出的客户的 cust_id 去查订单。
OrderMapper 接口中定义根据 cust_id 查询订单的方法:
OrderMapper 映射文件中写 SQL:
定义好接口中的方法后,CustomerMapper 映射文件中写 SQL,利用 collection 实现分步查询(与之前的 association 类似)。
测试类中:
运行结果:每个查询出来的用户,都会再根据他的 cust_id 去查询订单。但是由图可见,会产生很多的 sql 语句。(左连接只需要一句SQL)