1.嵌套结果查询
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.itsource._03_one2many.DomainMapper">
<!-- 自己设置映射关系 -->
<resultMap type="cn.itsource._03_one2many.Dept" id="deptMap">
<!-- 依然需要相应的设置 -->
<id property="id" column="id"/>
<result property="name" column="name"/>
<!-- 对应 private List<User> users = new ArrayList<>();里的users javaType指User -->
<collection property="users" javaType="cn.itsource._03_one2many.User">
<id property="id" column="uid"/>
<result property="name" column="uname"/>
<result property="password" column="password"/>
</collection>
</resultMap>
<select id="getDepts" resultMap="deptMap">
select d.id,d.name,u.id uid,u.name uname,u.password from t_dept d left join t_user u on u.dept_id = d.id
</select>
</mapper>
2.嵌套查询
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.itsource._03_one2many.DomainMapper">
<!-- 自己设置映射关系 -->
<resultMap type="cn.itsource._03_one2many.Dept" id="deptMap">
<id column="id" property="id"/>
<result column="name" property="name"/>
<!-- column="id"是指dept的ID ofType是指返回类型 -->
<collection property="users" ofType="cn.itsource._03_one2many.User" column="id" select="getUserByDeptId"/>
</resultMap>
<!-- 查询部门的员工 -->
<select id="getUserByDeptId" parameterType="cn.itsource._03_one2many.Dept">
select * from t_user where dept_id=#{id}
</select>
<select id="getDepts" resultMap="deptMap">
select * from t_dept
</select>
</mapper>