关于mybatis中mapper文件resultMap中collection和association的使用

1.  快速图

collection:

association:

2. 代码

1)实体类

@Data
public class Employee {
    private Long eid;

    private String username;

    private String password;

    private Role role;
}
@Data
public class Role {
    private Long rid;

    private String rname;

    /*一个角色可以有多个权限*/
    private List<Permission> permissions = new ArrayList<>();
}
@Data
public class Permission {
    private Long pid;

    private String pname;

    private String presource;
}

2)EmployeeMapper.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.djyz.mapper.EmployeeMapper" >


  <resultMap id="BaseResultMap" type="com.djyz.domain.Employee" >
    <id column="eid" property="eid" jdbcType="BIGINT" />
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <association property="role" resultMap="RoleResultMap"/>
  </resultMap>

  <resultMap id="RoleResultMap" type="com.djyz.domain.Role" >
    <id column="rid" property="rid" />
    <result column="rname" property="rname" />
    <collection property="permissions" ofType="com.djyz.domain.Permission">
      <id column="pid" property="pid" />
      <result column="pname" property="pname"  />
      <result column="presource" property="presource" />
    </collection>
  </resultMap>

  <select id="selectByPrimaryKey" resultMap="BaseResultMap"    parameterType="java.lang.Long">
    select * from employee e
    LEFT JOIN role r ON e.rid = r.rid
    LEFT JOIN role_permission_rel rel ON r.rid = rel.rid
    LEFT JOIN permission p ON rel.pid = p.pid
    where eid = #{eid,jdbcType=BIGINT}
  </select>
</mapper>

https://www.cnblogs.com/stefanking/articles/5092474.html

发布了48 篇原创文章 · 获赞 18 · 访问量 2798

猜你喜欢

转载自blog.csdn.net/weixin_44210965/article/details/105215152