User.java, Role.java,address.java为三个类
public class User {
.....//user自己的属性
//association一对一
private Role role;
//collection一对多
private List<Address> addressList;
}
//User的接口
//根据roleId获取用户列表assoction
public List<User> getUserListByRoleId(Role role);
//获取指定用户的地址列表collection
public User getAddressListByUserId(User user);
//sql
<!-- 根据roleId获取用户列表association start -->
<resultMap type="User" id="userMap">
<result property="id" column="id"/>
<result property="userCode" column="userCode"/>
<result property="userName" column="userName"/>
<!-- 方法一
<association property="role" javaType="Role">
<result property="id" column="r_id"/>
<result property="roleCode" column="roleCode"/>
<result property="roleName" column="roleName"/>
</association> -->
<!-- 方法二 -->
<association property="role" javaType="Role" resultMap="roleMap"></association>
</resultMap>
<resultMap type="Role" id="roleMap">
<result property="id" column="r_id"/>
<result property="roleCode" column="roleCode"/>
<result property="roleName" column="roleName"/>
</resultMap>
<select id="getUserListByRoleId" parameterType="Role" resultMap="userMap">
select u.*,r.id as r_id, r.roleName,r.roleCode from user u,role r
where u.roleId= r.id and r.id=#{id}
</select>
<!-- association end -->
<!-- 获取指定用户的地址列表collection 开始 -->
<resultMap type="User" id="searchMap">
<id property="id" column="userId"/>
<collection property="addressList" ofType="Address">
<!-- 此处id和result都可以 -->
<id property="id" column="a_id"/>
<result property="postCode" column="postCode"/>
<result property="addressContent" column="addressContent"/>
</collection>
</resultMap>
<select id="getAddressListByUserId" parameterType="User" resultMap="searchMap">
select *, a.id as a_id from user u,address a where u.id =a.userId and u.id=#{id}
</select>
<!-- collection end -->
为什么采用resultMap
1.resultMap仅用于联合查询并返回一个结果集,但属性名和数据库中的字段名不一致时
3.查询的属性结果集并不是都需要给用户