zoukankan      html  css  js  c++  java
  • mybatis的一对多双向映射

    连表查询
    select
    id
    resultType
    resultMap
    resultType和resultMap不能同时使用

    association 属性 映射到多对一中的“一”方的“复杂类型”属性,例如javabean user对象中嵌套一个复杂类型属性
    property 映射数据列的实体类属性 这里就是role
    javaType 完整java类名或者别名
    resultMap 引用外面的resultMap
    association 子元素
    id 主键id
    result 映射到javabean的某个“简单类型”的属性
    property 映射数据列的实体类属性
    column 数据库表字段或者别名
    collection属性 映射到一对多中的“多”方的“复杂类型”属性,例如集合 role对象中嵌套一个复杂类型属性
    property 映射数据列的实体类属性 这里就是user
    ofType 完整java类名或者别名
    resultMap 引用外面的resultMap

    多对一 “一”方
    实体类:
    public class User {

    private Integer id;
    private String userName;
    private String userPassword;
    //创建一个角色对象 作用是查看用户信息同时还要看角色信息
    private Role role;

    省略getter和setter方法
    }
    sql映射文件:
    <mapper namespace="com.y2196.dao.UserMapper">

    <resultMap type="com.y2196.entity.User" id="user">
    <id property="id" column="id"/>
    <result property="userName" column="userName"/>
    <result property="userPassword" column="userPassword"/>
    <!-- 多对一 “一”方 要使用association来映射-->
    <association property="role" javaType="com.y2196.entity.Role">
    <!-- 当有字段名相同的时候,要使用别名方式来区分 -->
    <id property="id" column="rid"/>
    <result property="roleName" column="roleName"/>
    </association>

    </resultMap>
    <!-- select标签 resultType和resultMap不能同时使用 -->
    <select id="findUserList" resultMap="user">
    SELECT u.*,r.id AS rid,r.roleName FROM `user` u INNER JOIN role r ON u.roleId = r.id
    </select>
    </mapper>


    一对多 “多”方
    实体类:
    public class Role {

    private Integer id;
    private String roleName;

    private List<User> userList;

    省略getter和setter方法
    }
    sql映射文件:
    <resultMap type="com.y2196.entity.Role" id="role">
    <!-- 当有字段名相同的时候,要使用别名方式来区分 -->
    <id property="id" column="rid"/>
    <result property="roleName" column="roleName"/>
    <collection property="userList" ofType="com.y2196.entity.User" resultMap="user"/>
    </resultMap>

    <select id="findRoleList" resultMap="role">
    SELECT u.*,r.id AS rid,r.roleName FROM `user` u INNER JOIN role r ON u.roleId = r.id
    </select>

  • 相关阅读:
    Winform Treeview 的按需加载
    Dynamic CRM 2013学习笔记(十)客户端几种查询数据方式比较
    Dynamic CRM 2013学习笔记(九)CrmFetchKit.js介绍:Fetchxml、多表联合查询, 批量更新
    Dynamic CRM 2013学习笔记(八)过滤查找控件 (类似省市联动)
    iOS Programming
    Hello Socket
    解决ARC的循环引用问题
    解决Eclipse下不自动拷贝apk到模拟器问题( The connection to adb is down, and a severe error has occured)
    解决Android NDK 报jxxx编译找不到
    做一个创建cocos2d-x新项目的shell脚本
  • 原文地址:https://www.cnblogs.com/zhuhuibiao/p/9825318.html
Copyright © 2011-2022 走看看