本节我们将介绍如何在实体类处理一对多的关系。
目录
1. mysql数据库关系结构
某个部门对应多个员工信息。
如: A部门 也就是我们标题的一, 张三和赵六,也就是我们标题的多。
2. 修改Dept实体类
Dept实体类需要添加“多”的信息,也就是emp员工信息。我们对应多个员工,则需要通过集合来实现,此处我们用List<emp> emp来添加完成,对应的需要新加get set方法以及重写toString方法。
package com.mybatis.pojo;
import java.util.List;
public class Dept {
private Integer did;
private String deptName;
private List<Emp> emp;
public Dept(Integer did, String deptName) {
this.did = did;
this.deptName = deptName;
}
public Dept() {
}
public List<Emp> getEmp() {
return emp;
}
public void setEmp(List<Emp> emp) {
this.emp = emp;
}
public Integer getDid() {
return did;
}
public void setDid(Integer did) {
this.did = did;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
@Override
public String toString() {
return "Dept{" +
"did=" + did +
", deptName='" + deptName + '\'' +
", emp=" + emp +
'}';
}
}
3.接口
我们在DeptMapper接口中添加如下信息:
DeptMapper.interfance
/**
* 获取部门以及部门中所有员工信息
*/
Dept getDeptAndEmp(@Param("did") Integer did);
3. mapper映射文件
我们需要编辑DeptMapper映射文件(一对多中一所在的映射文件)
resultMap和sql信息都在这里了。可以参考注释。
<resultMap id="deptAndEmpResultMap" type="Dept">
<!-- 主键字段: 主键实体类属性 和 数据库字段名-->
<id property="did" column="did"></id>
<!-- 普通字段: 属性和字段名-->
<result property="deptName" column="dept_name"></result>
<!-- 通过collection设置返回集合类, ofType设置是返回什么实体类的类型-->
<collection property="emp" ofType="Emp">
<!-- emp属性信息 对应 数据库表信息 具体设置 -->
<id property="eid" column="eid"></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>
<!-- Dept getDeptAndEmp(@Param("did") Integer did);-->
<select id="getDeptAndEmp" resultMap="deptAndEmpResultMap">
select * from t_dept t left join t_emp e on t.did = e.did where t.did =#{did};
</select>
4. 测试类
@Test
public void testGetDeptAndEmp(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
DeptMapper mapper = sqlSession.getMapper(DeptMapper.class);
Dept deptAndEmp = mapper.getDeptAndEmp(1);
System.out.println(deptAndEmp);
}
5. 测试结果
collection : 处理一对多的映射关系
ofType: 表示该属性对应集合中存储数据的类型