针对部门信息的查询 , 表, 数据, 实体类就不重复了, 可以看上一篇 mybatis 关联表[员工对部门]员工的查询 里面的创建语句
实体类肯定是要先有的
- 部门
public class Dept {
private int id;
private String name;
private List<Emp> emps;
// ...... Getter and Setter 请自行生成添加上
}
- 员工
public class Emp {
private int id;
private String name;
private String job;
private Date hiredate;
private int sal;
private int depId;
// ...... Getter and Setter 请自行生成添加上
}
controller , sevice 这里不描述了 . 基本一样
Repository的部分
@Repository
public interface DeptMapper {
Dept getDeptById(Integer id);
}
主要还是在xml的映射配置
- 第一种 :
- 其中的ofType指的是包含的集合中的类型
<?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="com.flynn.mapper.DeptMapper">
<resultMap id="BaseResultMap" type="com.flynn.bean.Dept">
<id property="id" column="d_id" jdbcType="INTEGER" />
<result property="name" column="d_name" jdbcType="VARCHAR" />
<collection property="emps" ofType="com.flynn.bean.Emp" >
<id property="id" column="e_id"/>
<result property="name" column="e_name"/>
<result property="job" column="e_job"/>
<result property="hiredate" column="e_hiredate"/>
<result property="sal" column="e_sal"/>
<result property="depId" column="e_dep_id"/>
</collection>
</resultMap>
<select id="getDeptById" resultMap="BaseResultMap">
SELECT
d.d_id,d.d_name,e.e_id,e.e_name,e.e_job,e.e_hiredate,e.e_sal,e.e_dep_id
FROM tb_dept d
INNER JOIN tb_emp e ON d.d_id = e.e_dep_id
WHERE d.d_id = #{id}
</select>
</mapper>
- 第二种 使用resultMap
<?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="com.flynn.mapper.DeptMapper">
<resultMap id="BaseResultMap" type="com.flynn.bean.Dept">
<id property="id" column="d_id" jdbcType="INTEGER" />
<result property="name" column="d_name" jdbcType="VARCHAR" />
<collection property="emps" ofType="com.flynn.bean.Emp" resultMap="empInfo"/>
</resultMap>
<resultMap id="empInfo" type="com.flynn.bean.Emp">
<id property="id" column="e_id"/>
<result property="name" column="e_name"/>
<result property="job" column="e_job"/>
<result property="hiredate" column="e_hiredate"/>
<result property="sal" column="e_sal"/>
<result property="depId" column="e_dep_id"/>
</resultMap>
<select id="getDeptById" resultMap="BaseResultMap">
SELECT
d.d_id,d.d_name,e.e_id,e.e_name,e.e_job,e.e_hiredate,e.e_sal,e.e_dep_id
FROM tb_dept d
INNER JOIN tb_emp e ON d.d_id = e.e_dep_id
WHERE d.d_id = #{id}
</select>
</mapper>