目录
一、mybatis解决多对一关系
1.1、方式一:级联属性赋值
对应的实体类,这里的构造方法,get,set方法,toString方法省略:
public class Emp {
private Integer id;
private String empName;
private Integer age;
private String sex;
private String email;
private Dept dept;
}
public class Dept {
private Integer did;
private String deptName;
}
在mapper接口定义方法:
/**
* 查询员工的信息和对应的方法
* @param id
* @return
*/
Emp selectEmp(@Param("id") Integer id);
在mybatis的mapper映射文件
<!--级联属性赋值-->
<resultMap id="empResultMap" type="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>
<result property="dept.did" column="did"></result>
<result property="dept.deptName" column="dept_name"></result>
</resultMap>
<select id="selectEmp" resultMap="empResultMap">
select * from t_emp left join t_dept on t_emp.did = t_dept.did where t_emp.id = #{id}
</select>
测试类:
@Test
public void test02(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
Emp emps = mapper.selectEmp(1);
System.out.println("emps = " + emps);
}
测试结果:
方式二、使用mybatis的association标签
其他不变,修改mybatis的mapper映射文件
<!--
association:专门处理多对一的关系
property:处理多对的映射关系的属性名
javaType:该属性的类型
-->
<resultMap id="empResultMap" type="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>
<association property="dept" javaType="Dept">
<id property="did" column="did"></id>
<result property="deptName" column="dept_name"></result>
</association>
</resultMap>
方式三、分步查询
第一步:
Emp selectEmpAndDept(@Param("id") Integer id);
修改 Emp的配置mapper映射文件
<resultMap id="empResultMap" type="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>
<association property="dept"
select="com.cjc.mybatis.mapper.DeptMapper.selectEmpAndDept"
column="did">
</association>
</resultMap>
<select id="selectEmpAndDept" resultMap="empResultMap">
select * from t_emp where id = #{id}
</select>
第二步:
Dept selectEmpAndDept(@Param("did") Integer did);
修改 Dept的配置mapper映射文件
<resultMap id="resultDept" type="dept">
<id property="did" column="did"></id>
<result property="deptName" column="dept_name"></result>
</resultMap>
<select id="selectEmpAndDept" resultMap="resultDept">
select * from t_dept where did = #{did}
</select>
测试代码:
@Test
public void test03(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
Emp emp = mapper.selectEmpAndDept(3);
System.out.println("emp = " + emp);
}
测试结果: