首页 > 其他 > 详细

mybatis-一对一和一对多映射

时间:2020-05-23 16:10:43      阅读:58      评论:0      收藏:0      [点我收藏+]

这里说的一对一和一对多指的是某一方为中心来看待的

一.一对一映射

  1.给order类添加一个属性对象user,如图:

技术分享图片

 

   2.现在比如查询全部有所属客户的订单,在映射文件配置如下:

    <!-- 除普通属性外,映射到属性对象中的属性 -->
    <resultMap type="Orders" id="orderList">
        <id property="id" column="id"/>
        <result property="userId" column="user_id"/>
        
        <association property="user" javaType="User">
            <id column="id" property="id" />
            <result property="username" column="username"/>
        </association>
    </resultMap>
    <!-- 查询所有订单 -->
    <select id="findOrderList" resultMap="orderList">
        select o.id, o.user_id, u.id, u.username 
        from orders o,user u
        where o.user_id = u.id
    </select>

  说一下,如果映射的对象A中的属性是对象B,则B里面的属性不会被映射到,需要手动映射,association表示一对一映射;

  再强调两点:

    >如果添加了association,如果想要将返回的结果集统一映射到每个属性上,就要指定想映射的属性,即使属性名和列名一致也不会自动映射

    >查询到的结果集避免出现不同表的相同主键名,这会导致是有一列无效的,就上述的代码就是个典型的示范,orders的主键列为id,user表的主键列还是id,如果返回的结果集包含这两列,靠后的一列是无效的

 

二.一对多映射

 

    <resultMap type="User" id="userList">
        <id property="id" column="id"/>
        <result property="username" column="username"/>
        
        <collection property="orders" ofType="Orders">
            <result property="number" column="number"/>
        </collection>
    </resultMap>

 

  1.一对多映射跟一对一的操作差不多,不过有一些小区别,colleaction用于一对多情况,ofType代表集合的泛型

 

mybatis-一对一和一对多映射

原文:https://www.cnblogs.com/ibcdwx/p/12942537.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!