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

  • 相关阅读:
    Bootstrap组件福利篇 网址
    <a>标签中的href="javascript:;"
    HTTP请求上下文之终结:HttpContext类
    数据库分离 附加 sqlserver
    C#中三层架构UI、BLL、DAL、Model实际操作(转)
    比较好的网上的sqlserver读书笔记
    ORACLE重建索引详解
    SQL Server遍历表的几种方法(转)
    提高数据库操作的效率(转)
    哈希表Hashtable与字典表Dictionary<K,V>的比较。
  • 原文地址:https://www.cnblogs.com/ibcdwx/p/12942537.html
Copyright © 2011-2022 走看看