MyBatis学习:高级映射之多对多查询
2021-02-28 本文已影响0人
ApesKingMan
用户表和商品表之间的多对多映射

因为多对多比较复杂,总公共有四张表,我们先来分析一下思路:

表有点多,关系有点复杂

接下来,写名为UserAndItemsResultMap的resultMap,由于主表查询的是User,所以在resultMap中的type应该写成User的完全限定名或者别名:

下面就是写mapper接口了:

测试一下:

多对多的映射就搞定了。就是这里多对多的查询会把所有关联的表的信息都查询出来,然后放到pojo中的对应的List或者某个类中,所以即使我只查了个用户信息,但是这个用户里包含了订单,订单项,商品等信息,
感觉装的有点多,好像有时候并不需要这么多冗余的数据出来,但是如果用resultType的话查询出来的字段必须对应pojo中的属性,如果有List等,需要手动装入才行。所以下面总结一下对于这种查询数据比较多的时候,resultType和resultMap各有什么作用?

mybatis的多对多映射就总结完了
参考:https://mp.weixin.qq.com/s/_gFvuyEi8PLUO8KokFreKw