MyBatis查询:多对一映射关系


通过级联属性复制解决多对一的映射关系

通过association解决多对一的映射关系

通过级联属性复制解决多对一的映射关系

Mapper层

@Mapper
public interface ParameterMapper {
    Emp GetEmpAndDept(@Param("id") Integer eid);
}

映射文件

<?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.example.mybatis_review.mapper.ParameterMapper">
    <resultMap id="GetEmpAndDeptMap" type="com.example.mybatis_review.bean.Emp">
        <id property="eid" column="eid">id>
        <result property="age" column="age">result>
        <result property="email" column="email">result>
        <result property="empName" column="emp_name">result>
        <result property="did" column="did">result>
        <result property="dept.did" column="did">result>
        <result property="dept.deptName" column="dept_name">result>
    resultMap>

    <select id="GetEmpAndDept" resultMap="GetEmpAndDeptMap">
        select * from t_emp left join t_dept on t_emp.did = t_dept.did where t_emp.eid=#{id}
    select>
mapper>

通过association解决多对一的映射关系

Mapper

@Mapper
public interface ParameterMapper {
    Emp GetEmpAndDept(@Param("id") Integer eid);
}

映射文件

<?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.example.mybatis_review.mapper.ParameterMapper">
    <resultMap id="GetEmpAndDeptMap" type="com.example.mybatis_review.bean.Emp">
        <id property="eid" column="eid">id>
        <result property="age" column="age">result>
        <result property="email" column="email">result>
        <result property="empName" column="emp_name">result>
        <result property="did" column="did">result>
        <association property="dept" javaType="com.example.mybatis_review.bean.Dept">
            <id property="did" column="did">id>
            <result property="deptName" column="dept_name">result>
        association>
    resultMap>

    <select id="GetEmpAndDept" resultMap="GetEmpAndDeptMap">
        select * from t_emp left join t_dept on t_emp.did = t_dept.did where t_emp.eid=#{id}
    select>
mapper>