mybatis处理一对多的映射关系
实体类
package org.example.entity; import java.util.List; public class Dept { private Integer deptId; private String deptName; private List<Emp> emps; public Dept() { } public Dept(Integer deptId, String deptName) { this.deptId = deptId; this.deptName = deptName; } public Integer getDeptId() { return deptId; } public void setDeptId(Integer deptId) { this.deptId = deptId; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } public List<Emp> getEmps() { return emps; } public void setEmps(List<Emp> emps) { this.emps = emps; } @Override public String toString() { return "Dept{" + "deptId=" + deptId + ", deptName='" + deptName + '\'' + ", emps=" + emps + '}'; } }
mapper接口
Dept getEmpAndDeptByDeptId(@Param("deptId") int deptId);
方式一:
collection 标签
<?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="org.example.mapper.DeptMapper"><resultMap id="empAndDeptResultMap" type="Dept"> <id column="dept_id" property="deptId"></id> <result column="dept_name" property="deptName"></result> <!-- collection:处理一对多的映射关系(处理集合类型的属性) ofType:设置集合类型的属性中存储的数据的类型 --> <collection property="emps" ofType="Emp"> <id column="emp_id" property="empId"></id> <result column="emp_name" property="empName"></result> <result column="age" property="age"></result> <result column="gender" property="gender"></result> </collection> </resultMap> <select id="getEmpAndDeptByDeptId" resultMap="empAndDeptResultMap"> select * from t_dept a left join t_emp b on a.dept_id = b.dept_id where a.dept_id = #{deptId} </select> </mapper>
方式二:
分布查询
DeptMapper接口
Dept getDeptAndEmpStepOne(@Param("deptId") int deptId);
EmpMapper接口
List<Emp> getDeptAndEmpStepTwo(@Param("deptId") Integer deptId);
DeptMapper.xml
<resultMap id="DeptAndEmpResultMapStepOne" type="Dept"> <id column="dept_id" property="deptId"></id> <result column="dept_name" property="deptName"></result> <collection property="emps" select="org.example.mapper.EmpMapper.getDeptAndEmpStepTwo" column="dept_id"> </collection> </resultMap> <select id="getDeptAndEmpStepOne" resultMap="DeptAndEmpResultMapStepOne"> select * from t_dept where dept_id = #{deptId} </select>
EmpMapper.xml
<select id="getDeptAndEmpStepTwo" resultType="org.example.entity.Emp"> select * from t_emp where dept_id = #{deptId} </select>
测试代码
@Test public void testGetDeptAndEmpByStep(){ SqlSession sqlSession = SqlSessionUtil.getSqlSession(); DeptMapper mapper = sqlSession.getMapper(DeptMapper.class); Dept dept = mapper.getDeptAndEmpStepOne(1); System.out.println(dept); sqlSession.close(); }
结果:
Dept{deptId=1, deptName='A', emps=[Emp{empId=1, empName='张三', age=10, gender='男', dept=null}, Emp{empId=4, empName='赵六', age=15, gender='男', dept=null}]}