数据库表
员工表(t_employee)
部门表(t_department)
表所对应的类
员工 t_employee
以通过部门id,查询部门信息,以及部门中所有员工信息为例。
接口
public interface DepartmentMapper {
//通过部门的did查询部门所有信息
Department selectDepartment(@Param("did")Integer did);
}
映射文件
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xxx.mapper.DepartmentMapper">
<resultMap id="deptMap" type="com.xxx.pojo.Department">
<id property="did" column="did">id>
<result property="dname" column="dname">result>
<collection property="emp" ofType="com.xxx.pojo.Employee">
<id property="eid" column="eid">id>
<result property="ename" column="ename">result>
<result property="age" column="age">result>
<result property="sex" column="sex">result>
collection>
resultMap>
<select id="selectDepartment" resultMap="deptMap">
select t_department.*,t_employee.* from t_department left join t_employee on t_department.did=t_employee.did where t_department.did=#{did}
select>
mapper>
测试
DepartmentMapper mapper = sqlSession.getMapper(DepartmentMapper.class);
//查询部门did=2的所有信息
Department department = mapper.selectDepartment(2);
System.out.println(department);
Department{did=2, dname='部门2', emp=[Employee{eid=4, ename='翠花', age=19, sex='女', dept=null}, Employee{eid=3, ename='小红', age=20, sex='女', dept=null}]}
以通过部门id,查询部门信息,以及部门中所有员工信息为例。
第一步接口
public interface DepartmentMapper {
//通过部门的did查询部门所有信息
Department selectDepartment(@Param("did")Integer did);
}
第二步接口
public interface EmployeeMapper {
//通过员工部门的did查询员工的所有信息
Employee selectEmployee(@Param("did")Integer did);
}
第一步映射文件
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xxx.mapper.DepartmentMapper">
<resultMap id="deptMap" type="com.xxx.pojo.Department">
<id property="did" column="did">id>
<result property="dname" column="dname">result>
<collection property="emp"
select="com.xxx.mapper.EmployeeMapper.selectEmployee"
column="did">collection>
resultMap>
<select id="selectDepartment" resultMap="deptMap">
select * from t_department where did=#{did}
select>
mapper>
第二步映射文件
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xxx.mapper.EmployeeMapper">
<select id="selectEmployee" resultType="com.xxx.pojo.Employee">
select * from t_employee where did=#{did}
select>
mapper>
测试
DepartmentMapper mapper = sqlSession.getMapper(DepartmentMapper.class);
//查询部门did=2的所有信息
Department department = mapper.selectDepartment(2);
System.out.println(department);
Department{did=2, dname='部门2', emp=[Employee{eid=4, ename='翠花', age=19, sex='女', dept=null}, Employee{eid=3, ename='小红', age=20, sex='女', dept=null}]}