一.如何处理多对多级联关系?
往往拆分成两个一对多级联来处理
例子
一个用户可以对应多个角色,而一个角色又可以由多个用户担当。
这个时候用户和角色是以一张用户角色表建立关联关系,用户和角色是多对多关系。
用户和角色的关系
用户POJO
角色POJO
两个List类型的属性是专门做一对多级联用的,使用collection元素去完成
角色RoleMapper.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="cn.whc.April_3.mapper.RoleMapper">
<resultMap id="roleMapper" type="cn.whc.April_3.pojo.Role">
<id column="id" property="id"/>
<result column="role_name" property="roleName"/>
<collection property="userList" column="id" select="cn.whc.April_3.mapper.UserMapper.findUserByRoleId" fetchType="lazy"/>
</resultMap>
<select id="getRole" parameterType="long" resultMap="roleMapper">
select id,role_name,note from t_role where id = #{id}
</select>
<select id="findRoleByUserId" parameterType="long" resultMap="roleMapper">
select r.id, r.role_name, r.note
from t_role r,t_user_role ur
where r.id = ur.role_id
and ur.user_id = #{userId}
</select>
</mapper>
用户UserMapper.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="cn.whc.April_3.mapper.UserMapper">
<resultMap id="userMapper" type="cn.whc.April_3.pojo.User">
<id column="id" property="id"/>
<result column="user_name" property="userName"/>
<result column="real_name" property="realName"/>
<result column="sex" property="sex" typeHandler="cn.whc.March_30.typeHandler.SexTypeHandler"/>
<result column="mobile" property="mobile"/>
<result column="email" property="email"/>
<result column="position" property="position"/>
<result column="note" property="note"/>
<collection property="roleList" column="id" select="cn.whc.April_3.mapper.RoleMapper.findRoleByUserId" fetchType="lazy"/>
</resultMap>
<select id="getUser" parameterType="long" resultMap="userMapper">
select id,user_name,real_name,sex,mobile,email,note
from t_user
where id = #{id}
</select>
<select id="findUserByRoleId" parameterType="long" resultMap="userMapper">
select u.id, u.user_name, u.real_name, u.sex, u.mobile, u.email,u.note
from t_user u,t_user_role ur
where u.id = ur.user_id
and ur.role_id = #{roleId}
</select>
</mapper>
两处的fetchType都设置为lazy,这样就能进行延迟加载了,另外在mybatis-config.xml中settings标签设置如下
<settings>
<!-- 开启延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 关闭层级加载 -->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
测试
@Test
public void test1(){
try {
Logger logger = Logger.getLogger(AppTest.class);
sqlSession = SqlSessionFactoryUtils.openSqlSession();
RoleMapper mapper = sqlSession.getMapper(RoleMapper.class);
// 查询编号为1的角色
Role role = mapper.getRole(1L);
// 查找角色为1所有用户的方法,开启延迟加载后,只有调用这个方法,才加载数据
role.getUserList();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUser(1L);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
}
效果