目录
一、mybtais实现一对多的映射关系
1.1、方式一:使用collection标签
实体类中省略get、set方法
public class Dept {
private Integer did;
private String deptName;
private List<Emp> emps;
}
mapper接口
Dept selectDeptAndEmp(@Param("did") Integer did);
mapper的映射文件
<resultMap id="resultDept" type="Dept">
<id property="did" column="did"></id>
<result property="deptName" column="dept_name"></result>
<collection property="emps" ofType="Emp">
<id property="id" column="id"></id>
<result property="empName" column="emp_name"></result>
<result property="age" column="age"></result>
<result property="sex" column="sex"></result>
<result property="email" column="email"></result>
</collection>
</resultMap>
<select id="selectDeptAndEmp" resultMap="resultDept">
select * from t_dept left join t_emp on t_dept.did = t_emp.did where t_dept.did = #{did}
</select>
测试类:
@Test
public void test04(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
DeptMapper mapper = sqlSession.getMapper(DeptMapper.class);
Dept dept = mapper.selectDeptAndEmp(1);
System.out.println("dept = " + dept);
}
1.2、方式二:使用分步查询的方式:
Dept selectEmpAndDept(@Param("did") Integer did);
<resultMap id="resultDept" type="Dept">
<id property="did" column="did"></id>
<result property="deptName" column="dept_name"></result>
<collection property="emps"
select="com.cjc.mybatis.mapper.EmpMapper.selectEmpAndDeptDid"
column="did">
</collection>
</resultMap>
<select id="selectEmpAndDept" resultMap="resultDept">
select * from t_dept where did = #{did}
</select>
List<Emp> selectEmpAndDeptDid(@Param("did") Integer did);
<select id="selectEmpAndDeptDid" resultType="emp">
select * from t_emp where did = #{did}
</select>