假设需要实现:根据id查询某个用户组的详情时,显示该组的所有用户的信息!
需要执行的SQL语句大致是:
select * from t_group left join t_user on t_group.id=t_user.group_id where t_group.id=1;首先,需要在项目中创建新的GroupVO类,用于封装查询结果:
public class GroupVO {
private Integer id;
private String name;
private List<User> users;
}在GroupMapper接口中添加抽象方法:
GroupVO findVOById(Integer id);在GroupMapper.xml文件中配置SQL映射:
<resultMap id="GroupMap" type="cn.tedu.spring.GroupVO">
<id column="gid" property="id" />
<result column="name" property="name" />
<!-- collection节点:用于配置1对多的属性,也就是List集合类型的属性 -->
<!-- ofType属性:List集合中的元素的类型 -->
<!-- 在collection节点的子级的各id、result节点中的property指的是ofType的类中的属性名 -->
<collection property="users" ofType="cn.tedu.spring.User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="age" property="age"/>
<result column="phone" property="phone"/>
<result column="email" property="email"/>
<result column="group_id" property="groupId"/>
</collection>
</resultMap>
<select id="findVOById" resultMap="GroupMap">
SELECT
t_group.id AS gid, name,
t_user.*
FROM
t_group
LEFT JOIN
t_user
ON
t_group.id=t_user.group_id
WHERE
t_group.id=#{id}
</select>Integer作为返回值类型;如果是查询类型的操作,可以使用期望的类型作为返回值类型,只要能把查询结果封装进去就行;@Param注解。<mapper>中配置namespace属性指定对应的接口文件;<insert>、<delete>、<update>、<select>节点,每个节点都必须配置id属性指定对应的抽象方法的名称,<select>还必须配置resultType或resultMap中的某1个属性。#{}和${}格式的占位符的区别;
<resultMap>节点,以指定MyBatis框架完成封装过程。<foreach>节点的使用;
<if>和<choose>系列节点的使用;
<resultMap>的配置与使用;
*)表示字段列表,且存在名称不匹配的问题时,例如实现1对1的关联查询时;<resultMap>:
*)表示字段列表,且存在名称不匹配的问题时,配置<resultMap>便于应用到多个不同的查询中;