MyBatis关联查询

Categories:

mybatis中一对多和多对一的配置


一对一,多对一

 

员工实体类

public class Employee {
    private Integer id;
    private String name;
    private Dept dept;
    //set、get方法略
}

员工resultMap

<resultMap id="employeeMap" type="Employee">
    <id property="id" column="ID"/>
    <result property="name" column="NAME"/>
    <result property="dept.id" column="DEPT_ID"/>
    <result property="dept.name" column="DEPT_NAME"/>
</resultMap>

查询员工时查询部门名称

<select id="getEmployeeWithDept" resultMap="employeeMap">
    select E.ID, E.NAME, E.DEPT_ID, D.NAME DEPT_NAME
    from EMPLOYEE E
    inner join DEPT D ON E.DEPT_ID=D.ID
</select>

一对多,多对多

 

部门实体类

public class Dept {
    private Integer id;
    private String name;
    private List<Employee> employees;
    // set、get方法略
}

部门resultMap:resultMap可以继承

<resultMap id="deptMap" type="Dept">
    <id property="id" column="ID"/>
    <result property="name" column="NAME"/>
</resultMap>
<resultMap id="deptMapWithEmployee" type="Dept" extends="deptMap">
    <collection property="employees" ofType="Employee" >
        <id property="id" column="EMP_ID"/>
        <result property="name" column="EMP_NAME"/>
    </collection>
</resultMap>

通过部门id查询员工信息

<select id="getEmpByDept" resultMap="employeeMap" parameterType="int">
    select ID,NAME FROM EMPLOYEE where DEPT_ID=#{deptid}
</select>