zoukankan      html  css  js  c++  java
  • mybatis-一对一和一对多映射

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

    一.一对一映射

      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代表集合的泛型

  • 相关阅读:
    layui 相关知识
    ideal debug 启动不起来
    删除命令 rm -rf maven-project-jxcg.zip 解压 unzip maven-project-jxcg.zip
    vsb 配置
    cmd dos
    switch
    Element UI 框架搭建
    mysql 远程连接设置
    YApi可视化接口管理平台 接口
    报403错误
  • 原文地址:https://www.cnblogs.com/ibcdwx/p/12942537.html
Copyright © 2011-2022 走看看