13-一对多左连接查询&分步查询(查询所有客户及客户对应的订单)

查询所有客户以及对应的订单

目录


 

左连接查询(不支持懒加载)

场景:我们想要查询出所有的客户,并且把每个客户对应的订单也查出来。这时候可以使用左连接查询。
在这里插入图片描述

那么如何在 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)
在这里插入图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

军刀0923

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值