association用于1对1, 想不出有什么是1对1的, 如果1对1能不能他娘的直接一个表搞定了?
collection用于1对多, model里面有个list,例如user类里面有个roleList:
private List<SysRole> roleList;
在mapper的xml里面, 首先是extends原本的resultMap
<resultMap id="userRoleListMap" extends="userMap" type="marc.mybatis.lesson1.model.SysUser"> <collection property="roleList" columnPrefix="role_" resultMap="marc.mybatis.lesson1.mapper.SysRoleMapper.roleMap" /> </resultMap>
至于userMap是这样的.
<resultMap id="userMap" type="marc.mybatis.lesson1.model.SysUser"> <id property="id" column="id" /> <result property="userName" column="user_name" /> <result property="userPassword" column="user_password" /> <result property="userEmail" column="user_email" /> <result property="userInfo" column="user_info" /> <result property="headImg" column="head_img" jdbcType="BLOB" /> <result property="createTime" column="create_time" jdbcType="TIMESTAMP" /> </resultMap>
而roleMap是在另一个mapper的xml文件里面:
<resultMap id="roleMap" type="marc.mybatis.lesson1.model.SysRole"> <id property="id" column="id" /> <result property="roleName" column="role_name" /> <result property="enabled" column="enabled" /> <result property="createBy" column="create_by" /> <result property="createTime" column="create_time" jdbcType="TIMESTAMP" /> </resultMap>
就这么简单, 加上service的interface之后就可以测试了:
SysUser selectUserRoleListMap(@Param("id") Long id);
测试类如下, 省略baseTester:
@Test public void testSelectUserRoleListMap() { SqlSession sqlSession = getSqlSession(); try { UserMapper userMapper = sqlSession.getMapper(UserMapper.class); SysUser resultUser = userMapper.selectUserRoleListMap(1L); System.out.println(resultUser); } finally { sqlSession.close(); } }
哦, 忘了贴xml里面的select了
<select id="selectUserRoleListMap" resultMap="userRoleListMap"> select u.id, u.user_name, u.user_password, u.user_email, u.user_info, u.head_img, u.create_time, r.id role_id, r.role_name role_role_name, r.enabled role_enabled, r.create_by role_create_by, r.create_time role_create_time from sys_user u inner join sys_user_role ur on u.id = ur.user_id inner join sys_role r on ur.role_id = r.id where u.id = #{id} </select>
滑稽的地方是, role_role_name, 太特么不优雅了...一开始role表的字段就不应该叫role_name, 傻...