多彩编程 多彩编程MZPH · CODE BLOG
ARTICLE DETAIL

文章详情

深耕前端与后端开发技术的一线实战笔记与踩坑复盘。

Mybatis的多表操作问题

Mybatis的多表操作问题 第二张图的association 和 第一张图的一样Q1 一对一表关系之中哪个属性封装到ResultMap中哪一个封装到association当中?A主要看谁包含谁例如一个用户 (User) 持有一张身份证 (IdCard)// User 主实体 public class User{ private Integer id; private String name; // User里面包含 IdCard 对象 private IdCard idCard; } public class IdCard{ private Integer cid; private String cardNo; }User 是外层主体resultMap 的typeUseridCard是 User 的内部成员单个对象 所以在 User 的 resultMap 里面写。resultMap idUserMap typeUser id columnu_id propertyid/ result columnu_name propertyname/ !-- User里面装着idCard所以association写idCard -- association propertyidCard javaTypeIdCard id columncid propertycid/ /association /resultMap一句话总结规则resultMap 的 type 指定「外层大对象」association 的 property 写「外层对象里面包含的成员对象」。order表内部还包含了user 的信息Q2一对多一对多表关系之中哪个属性封装到ResultMap中哪一个封装到collection当中?collection的作用封装【集合类型属性】ListT / SetT。所以哪一个有集合哪一个就被封装。查询场景查询一个用户名下的所有订单// User一个用户 public class User { private Integer id; private String name; // 一个用户 → 多个订单集合 private ListOrder orderList; } // Order多个订单 public class Order { private Integer oid; private String orderName; private Integer userId; // 一个订单 → 归属一个用户【单个对象】不是List private User user; }所以把OrderList封装进collection中resultMap idUserWithOrderMap typecom.entity.User !-- 用户自身字段 -- id columnu_id propertyid/ result columnu_name propertyname/ !-- User内部属性ListOrder orderList 【集合】 一对多 → 使用 collection propertyUser里集合属性名 orderList ofType集合里面元素类型 Order -- collection propertyorderList ofTypecom.entity.Order id columno_oid propertyoid/ result columno_order_name propertyorderName/ /collection /resultMap查询用户下属的订单有哪些多对多查询多对多的键表原则是必须要引入一张中间表即上图中的user_role表查询语句以及查询结果如下
返回列表