什么时候需要使用结果集映射?
- 当实体类中的字段与sql查询的字段不一致时使用(也可以用sql别名解决)
- 若是实体类的字段中出现对象或者列表,需要使用association/collection进行映射
1. 简单结果
<resultMap id="userResultMap" type="User">
<id property="id" column="user_id" />
<result property="username" column="user_name"/>
<result property="password" column="hashed_password"/>
</resultMap>
其中,column对应数据库的字段,property对应实体类字段。
2. 多对一
实体类User中有
private Role userRole;
属性,但是数据库查询的字段中没有与之匹配的字段,因此需要结果集映射,通过association
查询role表得到相关信息与之进行匹配
-
UserMapper中定义方法
// 查询用户列表包含其对应的角色名称 List<User> getUserListWithRole();
-
UserMapper.xml实现方法
方式一:
<!--查询所有的用户,但结果集由于数据库字段和User属性不统一,需要映射--> <select id="getUserListWithRole" resultMap="UserWithRoleName"> select * from smbms_user; </select> <!--映射上面方法结果集,只需要将userRole字段映射到userRole属性上即可,映射的内容需要select查询,返回结果为javaType=Role--> <resultMap id="UserWithRoleName" type="User"> <association property="userRole" javaType="Role" column="userRole" select="getRole"/> </resultMap> <!--根据id查询角色,查询的字段应当与Role实体类对应,传给上面--> <select id="getRole" resultType="Role"> select * from smbms_role where id = #{id} </select>
方式二:(若需要查出所有的属性,sql语句中需要全部写出,且进行映射)
<select id="getUserListWithRole2" resultMap="UserWithRoleName2"> select u.id uid, u.userName uname, r.roleName rname from smbms_user u, smbms_role r where r.id = u.userRole </select> <resultMap id="UserWithRoleName2" type="User"> <result property="id" column="uid"/> <result property="userName" column="uname"/> <association property="userRole" javaType="Role"> <result property="roleName" column="rname"/> </association> </resultMap>
3. 一对多
实体类中的Role实体类有
private List<User> userList;
属性,但数据库查询后没有与之匹配的字段,因此需要再通过id
查询user表中对应的用户
-
UserMapper中定义方法
// 查询某个角色以及其对应的用户列表 Role getRoleWithUsers(Long id);
-
UserMapper.xml实现方法
方式一:
<!--查询某个角色以及其对应的用户列表--> <select id="getRoleWithUsers" resultMap="roleWithUsers"> select * from smbms_role where id = #{id} </select> <resultMap id="roleWithUsers" type="Role"> <id property="id" column="id"/> <collection property="userList" javaType="List" ofType="User" select="getUserById" column="id"/> </resultMap> <select id="getUserById" resultType="User"> select * from smbms_user where id = #{id} </select>
方式二:
<select id="getRoleWithUsers2" resultMap="roleWithUsers2"> select r.id rid, r.roleName rname, u.userName uname from smbms_role r, smbms_user u where r.id = #{id} and u.userRole = r.id </select> <resultMap id="roleWithUsers2" type="Role"> <result property="id" column="rid"/> <result property="roleName" column="rname"/> <collection property="userList" javaType="List" ofType="User"> <result property="userName" column="uname"/> </collection> </resultMap>