标签:class return nal 整理 imp on() lse maps sse
在一对一映射中,将User和Role的假设成为一对一映射关系。但在实际场景中,一个User往往同时可以拥有很多角色,在以下内容将上一篇内容稍作修改,来说明一对多映射(collection)的使用。
首先,将User类中的role属性修改为集合形式,并将UserMapper.xml中的userRoleMapperSelect中的association替换为collection标签,将原查询中关联表相关语句删除:
/** * 角色 */ private List<SysRole> roleList; public List<SysRole> getRoleList() { return roleList; } public void setRoleList(List<SysRole> roleList) { this.roleList = roleList; }
<resultMap id="userRoleMapSelect" type="tk.mybatis.simple.model.SysUser" extends="userMap"> <!--<association property="role" column="role_id" javaType="tk.mybatis.simple.model.SysRole" select="tk.mybatis.simple.mapper.RoleMapper.selectById" fetchType="lazy"/>--> <collection property="roleList" column="id" fetchType="lazy" select="tk.mybatis.simple.mapper.RoleMapper.selectAllByUserId"/> </resultMap> <select id="selectUserByRoleIdSelect" resultMap="userRoleMapSelect"> select u.id, u.user_name, u.user_password, u.user_email, u.user_info, u.head_img, u.create_time from sys_user u where u.id = #{id} </select>
然后,在RoleMapper中添加新的方法selectAllByUserId:
@ResultMap("roleResultMap") @Select("select * from sys_role " + "where id in(" + "select role_id from sys_user_role where user_id = #{userId}" + ")") List<SysRole> selectAllByUserId(Long userId);
修改并运行测试方法:
@Test public void testSelectUserAndRoleBySelect() { SqlSession sqlSession = getSqlSession(); try { UserMapper userMapper = sqlSession.getMapper(UserMapper.class); SysUser user = userMapper.selectUserByRoleIdSelect(1L); Assert.assertNotNull(user); // Assert.assertNotNull(user.getRole()); Assert.assertEquals(user.getRoleList().size(), 2); } finally { sqlSession.close(); } }
以上内容整理自《MyBatis从入门到精通》
标签:class return nal 整理 imp on() lse maps sse
原文地址:https://www.cnblogs.com/fantastic-clouds/p/13243533.html