1. 程式人生 > >MyBatis 多對多級聯

MyBatis 多對多級聯

在MyBatis中會拆分為兩個一對多關係。
比如: 使用者、角色 就是多對多關係,在做的時候就會拆分兩個一對多,及一個使用者多多個角色,一個角色對多個使用者。
中間還需要一個關聯表
entity:

  public class User2 {
    private Long id;
    private String userName;
    private String realName;
    private SexEnum sex;
    private String mobile;
    private String email;
    private String note;
    private
List<Role2> roleList; } public class Role2 { private Long id; private String roleName; private String note; private List<User2> userList; }

XML:

<mapper namespace="com.bob.analyst.dao.RoleMapper2">
      <resultMap type="com.bob.analyst.model.Role2" id="roleMapper"
>
<id column="id" property="id"/> <result column="role_name" property="roleName"/> <result column="note" property="note"/> <!-- 一對多 --> <collection property="userList" column="id" fetchType="lazy" select="com.bob.analyst.dao.UserMapper2.findUserByRoleId"
>
</collection> </resultMap> <select id="getRole" parameterType="long" resultMap="roleMapper"> select id,role_name as roleName,note from tbl_role where id=#{id} </select> <select id="findRoleByUserId" parameterType="long" resultMap="roleMapper"> select r.id,r.role_name,r.note from tbl_role r,tbl_user_role ur where r.id=ur.role_id and r.user_id=#{userId} </select> </mapper>
<mapper namespace="com.bob.analyst.dao.UserMapper2">
      <resultMap type="com.bob.analyst.model.User2" id="userMapper">
        <id column="id" property="id"/>
        <result column="user_name" property="userName"/>
        <result column="real_name" property="realName"/>
        <result column="sex" property="sex" typeHandler="com.bob.analyst.util.SexEnum"/>
        <result column="mobile" property="mobile"/>
        <result column="email" property="email"/>
        <result column="note" property="note"/>

        <!-- 一對多 -->
        <collection property="roleList" column="id" fetchType="lazy"
         select="com.bob.analyst.dao.RoleMapper2.findRoleByUserId"></collection>

      </resultMap>

      <cache type="com.xx.xx.xx.xxxCache">
        <property name="host" value="localhost"/>
      </cache>
      <cache-ref namespace="com.bob.analyst.dao.RoleMapper2"/>

      <select id="getUser" parameterType="long" resultMap="userMapper">
        select * from tbl_user
        where id=#{id}
      </select>

      <select id="findRoleByUserId" parameterType="long" resultMap="userMapper">
        select u.* from tbl_user u,tbl_user_role ur
        where u.id=ur.user_id and r.role_id=#{roleId}
      </select>

</mapper>

service:

Role2 role=roleMapper.getRole(1L);
role.getUserList();
User2 user=userMapper.getUser(1L);
user.getRoleList();