上一篇文章我们讲了Mybatis处理多对一的映射处理,这篇我们讲一下Mybatis如何处理一对多的处理。
使用collection连表查询的方式
Dept getDeptById(@Param("did") int did);
<resultMap id="abc" type="com.csdn.beans.Dept">
<id property="did" column="did"/>
<result property="dname" column="dname"/>
<collection property="emps" ofType="com.csdn.beans.Emp">
<id property="eid" column="eid"></id>
<result property="empName" column="emp_name"/>
<result property="empAge" column="emp_age"/>
<result property="empSex" column="emp_sex"/>
<result property="empEmail" column="emp_email"/>
</collection>
</resultMap>
<select id="getDeptById" resultMap="abc">
select * from dept left join emp on did=dept_id where did=#{did}
</select>
测试
SqlSession sqlSession= SqlSessionUtil.getSqlSession();
DeptMapper mapper = sqlSession.getMapper(DeptMapper.class);
Dept dept = mapper.getDeptById(1);
System.out.println(dept);
输出
Dept(did=1, dname=部门A, emps=[Emp{eid=1, empName='zhangsan', empAge=45, empSex='男', empEmail='bac@126.com'}, Emp{eid=2, empName='李四', empAge=55, empSex='男', empEmail='bac@126.com'}])
分步查询
一查询部门信息
Dept selectOne(@Param("did") int did);
<resultMap id="bbc" type="com.aoshen.beans.Dept">
<id property="did" column="did"/>
<result property="dname" column="dname"/>
<collection property="emps" ofType="com.aoshen.beans.Emp" select="com.aoshen.mapper.EmpMapper.selectTwo" column="did"></collection>
</resultMap>
<select id="selectOne" resultMap="bbc">
select * from dept where did=#{did}
</select>
查询emp信息
List<Emp> selectTwo(@Param("did") int did);
<resultMap id="abc" type="com.aoshen.beans.Emp">
<id property="eid" column="eid"></id>
<result property="empName" column="emp_name"/>
<result property="empAge" column="emp_age"/>
<result property="empSex" column="emp_sex"/>
<result property="empEmail" column="emp_email"/>
<result property="dept.did" column="did"/>
<result property="dept.dname" column="dname"/>
</resultMap>
<select id="selectTwo" resultMap="abc">
select * from emp where dept_id=#{did}
</select>
测试
@Test
public void test5(){
SqlSession sqlSession= SqlSessionUtil.getSqlSession();
DeptMapper mapper = sqlSession.getMapper(DeptMapper.class);
Dept dept = mapper.selectOne(2);
System.out.println(dept);
}
结果
Dept(did=2, dname=部门B, emps=[Emp{eid=3, empName='王五', empAge=21, empSex='男', empEmail='bac@126.com'}, Emp{eid=4, empName='赵六', empAge=32, empSex='女', empEmail='bac@126.com'}])