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>

  • 相关阅读:
    jquery.FixedColumns 滚动兼容问题
    面向对象三大特性:继承、封装、多态
    jquery.chosen.js和select2使用笔记
    Git查看、删除、重命名远程分支和tag(转载)
    GIT忽略追踪文件
    git代码量统计(转载)
    SQL SERVER如何收缩日志-通过脚本收缩(转发)
    GIT常用命令
    解决 git extensions 每次提交需要输入用户名和密码
    Mysql 5.7初始化密码
  • 原文地址:https://www.cnblogs.com/zhuhuibiao/p/9825318.html
Copyright © 2011-2022 走看看