【MyBatis笔记】7 - 自定义映射resultMap,处理一对多/多对一映射关系,处理属性字段一致性,MyBatis懒加载

视频链接:https://www.bilibili.com/video/BV1VP4y1c7j7?p=48&spm_id_from=pageDriver

准备工作

(1)新建maven工程

步骤详见:https://editor.csdn.net/md/?articleId=123185097

(2)在sql中建立两张表单:t_emp、t_dept

t_dept表单:
在这里插入图片描述

t_emp表单:
在这里插入图片描述

再添加一个did与dept表单的主键连接起来。
在这里插入图片描述

插入一些测试数据:
在这里插入图片描述
在这里插入图片描述

(3)建立mapper、pojo、映射文件

在这里插入图片描述

mapper接口

public interface EmpMapper {
}
public interface DeptMapper {
}

pojo

Dept pojo:

package com.atguigu.mybatis.pojo;

public class Dept {
    private Integer did;
    private String deptName;

    @Override
    public String toString() {
        return "Dept{" +
                "did=" + did +
                ", deptName='" + deptName + '\'' +
                '}';
    }

    public Integer getDid() {
        return did;
    }

    public void setDid(Integer did) {
        this.did = did;
    }

    public String getDeptName() {
        return deptName;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }

    public Dept() {
    }

    public Dept(Integer did, String deptName) {
        this.did = did;
        this.deptName = deptName;
    }
}

Emp pojo :

package com.atguigu.mybatis.pojo;

/**
 * @author Chen Ruoyi
 * @date 2022/3/1 9:07 PM
 */
public class Emp {
    private Integer eid;
    private String empName;
    private Integer age;
    private String sex;
    private String email;

    public Emp() {
    }

    public Emp(Integer eid, String empName, Integer age, String sex, String email) {
        this.eid = eid;
        this.empName = empName;
        this.age = age;
        this.sex = sex;
        this.email = email;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "eid=" + eid +
                ", empName='" + empName + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", email='" + email + '\'' +
                '}';
    }

    public Integer getEid() {
        return eid;
    }

    public void setEid(Integer eid) {
        this.eid = eid;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

xxxMapper.xml

DeptMapper.xml

<?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.atguigu.mybatis.mapper.DeptMapper">

</mapper>

EmpMapper.xml

<?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.atguigu.mybatis.mapper.EmpMapper">

</mapper>

1、resultMap处理字段和属性的映射关系

若字段名和实体类中的属性名不一致,但是字段名符合数据库的规则(使用_),实体类中的属性 名符合Java的规则(使用驼峰)

此时也可通过以下两种方式处理字段名和实体类中的属性的映射关系

  • a>可以通过为字段起别名的方式,保证和实体类中的属性名保持一致
  • b>可以在MyBatis的核心配置文件中设置一个全局配置信息mapUnderscoreToCamelCase,可 以在查询表中数据时,自动将_类型的字段名转换为驼峰
    例如:字段名user_name,设置了mapUnderscoreToCamelCase,此时字段名就会转换为 userName

1.1 用起别名的方式保证字段名与属性名一致

和sql中一样,用字段名 属性名(如emp_name empName)来使二者一致。

<!--    List<Emp> getAllEmp();-->
    <select id="getAllEmp" resultType="Emp">
        select eid, emp_name empName, age, sex, email from t_emp
    </select>

1.2 逐一设置resultMap映射关系

resultMap中,一一对应地设置属性名->字段名,再在select标签中添加resultMap="对应resultMap的id"

<!--
        resultMap设置自定义映射关系
        id      唯一标识
        type    映射的实体类型

        子标签:id 设置主键的映射关系, result设置其他的映射关系
            property    设置映射关系中的属性名,必须是type属性所设置的实体类类型的属性名
            column      设置映射关系中的字段名,必须是sql语句查询出来的字段名

        如果使用resultMap,就所有属性都需要设置
-->
    <resultMap id="empResultMap" type="Emp">
        <id property="eid" column="eid"></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>
    </resultMap>

    <select id="getAllEmp" resultMap="empResultMap">
        select * from t_emp
    </select>

1.3 配置mapUnderscoreToCamelCase

在全局配置文件mybatis-config.xml中,加入如下属性配置信息:

<!--    设置MyBatis的全剧配置-->
    <settings>
<!--        将下划线自动映射成驼峰,比如emp_name -> empName -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

2、多对一映射关系

如:查询员工信息以及员工所对应的部门信息

⚠️ 需要查询一对多、多对一的关系,需要在“一”的pojo中加入List<多>属性,在“多”的pojo中加入“一”。
⚠️ 也就是说,在Dept类中,要加入private List<Emp> emps;;在Emp类中,要加入private Dept dept;。然后给他们各自添加get、set方法,重写构造器和toString()

2.1 级联方式处理映射关系

EmpMapper.xml中:

<!--    多对一映射关系,方式一:级联属性赋值-->
    <resultMap id="getEmpAndDeptResultMapOne" type="Emp">
        <id property="eid" column="eid"></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>

<!--        Emp getEmpAndDept(@Param("eid") Integer eid);-->
    <select id="getEmpAndDept" resultMap="getEmpAndDeptResultMapOne">
        select * from t_emp left join t_dept
            on t_emp.eid = t_dept.did WHERE t_emp.eid = #{eid}
    </select>

EmpMapper类中

public interface EmpMapper {
    /**
     * 查询员工及其所对应的部门信息
     */
    Emp getEmpAndDept(@Param("eid") Integer eid);
}

测试类中:

    /**
     * 处理多对一的映射关系
     * a> 级联属性赋值
     * b> association
     * c> 分步查询
     */
    @Test
    public void testGetEmpAndDept(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        Emp empAndDept = mapper.getEmpAndDept(3);
        System.out.println(empAndDept);
    }

2.2 使用association处理映射关系

EmpMapper.xml:

<resultMap id="empDeptMap" type="Emp">
    <id column="eid" property="eid"></id>
    <result column="ename" property="ename"></result>
    <result column="age" property="age"></result>
    <result column="sex" property="sex"></result>
    <association property="dept" javaType="Dept">
        <id column="did" property="did"></id>
        <result column="dname" property="dname"></result>
    </association>
</resultMap>
<!--Emp getEmpAndDeptByEid(@Param("eid") int eid);-->
<select id="getEmpAndDeptByEid" resultMap="empDeptMap">
    select emp.*,dept.* from t_emp emp left join t_dept dept on emp.did =
dept.did where emp.eid = #{eid}
</select>

2.3 分步查询

(1) 查询员工信息

EmpMapper类中:

public interface EmpMapper {
	/**
	* 通过分步查询查询员工信息 * @param eid
	* @return
	*/
	Emp getEmpByStep(@Param("eid") int eid);
}

EmpMapper.xml

<!--    com.atguigu.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo是这条sql语句的全类名-->
    <resultMap id="getEmpAndDeptByStepResultMap" type="Emp">
        <id property="eid" column="eid"></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>
<!--
        select: 设置分步查询的sql的唯一标识(namespace.SQLId或mapper接口的全类名.方法名)
        column:分步查询的条件
        fetchType: 当开启了全局的延迟记载后,可通过此属性手动控制延迟加载的效果
        fetchType:"lazy/eager" lazy表示延迟加载,eager表示立即加载
-->
        <association property="dept"
                     select="com.atguigu.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo"
                     column="did"
                     fetchType="eager">
        </association>
    </resultMap>
    
<!--    Emp getEmpAndDeptByStepOne(@Param("eid") Integer eid);-->
    <select id="getEmpAndDeptByStepOne" resultMap="getEmpAndDeptByStepResultMap">
        select * from t_emp where eid = #{eid}
    </select>

(2) 根据员工所对应的部门id查询部门信息

DeptMapper接口:

public interface DeptMapper {
	/**
	* 分步查询的第二步:根据员工所对应的did查询部门信息
	*/
	Dept getEmpDeptByStep(@Param("did") int did);
}

DeptMapper.xml:

<!--        Dept getEmpAndDeptByStepTwo(Integer did);-->
<!--    分步查询可以实现懒加载-->
    <select id="getEmpAndDeptByStepTwo" resultType="Dept">
        select * from t_dept where did = #{did}
    </select>

⭕️ 延迟加载

分步查询的优点:可以实现延迟加载,但是必须在核心配置文件中设置全局配置信息:

  • lazyLoadingEnabled:延迟加载的全局开关。当开启时,所有关联对象都会延迟加载
  • aggressiveLazyLoading:当开启时,任何方法的调用都会加载该对象的所有属性。 否则,每个 属性会按需加载

此时就可以实现按需加载,获取的数据是什么,就只会执行相应的sql。此时可通过association和 collection中的fetchType属性设置当前的分步查询是否使用延迟加载,fetchType=“lazy(延迟加 载)|eager(立即加载)”
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

通过fetchType参数,可以手动控制延迟加载或立即加载,否则根据全局配置的属性决定是延迟加载还是立即加载。
在这里插入图片描述

3、一对多映射关系

根据部门id查找部门以及部门中的员工信息

⚠️ 需要查询一对多、多对一的关系,需要在“一”的pojo中加入List<多>属性,在“多”的pojo中加入“一”。
⚠️ 也就是说,在Dept类中,要加入private List<Emp> emps;;在Emp类中,要加入private Dept dept;。然后给他们各自添加get、set方法,重写构造器和toString()

3.1 collection

DeptMapper接口

public interface DeptMapper {
    /**
     * 获取部门以及部门中所有的员工信息
     */
    Dept getDeptAndEmp(@Param("did") Integer did);
 }

DeptMapper.xml

    <resultMap id="deptAndEmpResultMap" type="Dept">
        <id property="did" column="did"></id>
        <result property="deptName" column="dept_name"></result>
<!--
            collection:处理一对多的映射关系
            ofType:表示该属性对应的集合中存储数据的类型
-->
        <collection property="emps" ofType="Emp">
            <id property="eid" column="eid"></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>
        </collection>
    </resultMap>
<!--        Dept getDeptAndEmp(@Param("did") Integer did);-->
    <select id="getDeptAndEmp" resultMap="deptAndEmpResultMap">
        select * from t_dept left join t_emp on t_dept.did = t_emp.did where t_dept.did = #{did}
    </select>

测试类

    @Test
    public void testGetDeptAndEmp(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        DeptMapper mapper = sqlSession.getMapper(DeptMapper.class);
        Dept dept = mapper.getDeptAndEmp(1);
        System.out.println(dept);
    }

3.2 分步查询

(1)查询部门信息

DeptMapper接口

public interface DeptMapper {
    /**
     * 分步查询 查询部门及其所有的员工信息
     * 第一步  查询部门信息
     */
    Dept getDeptAndEmoByStepOne(@Param("did") Integer did);
}

DeptMapper.xml

<!--    分步查询-->
    <resultMap id="deptAndEmoByStepOneMap" type="Dept">
        <id property="did" column="did"></id>
        <result property="deptName" column="dept_name"></result>
        <collection property="emps"
                    select="com.atguigu.mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo"
                    column="did">
        </collection>
    </resultMap>
<!--        Dept getDeptAndEmoByStepOne(@Param("did") Integer did);-->
    <select id="getDeptAndEmoByStepOne" resultMap="deptAndEmoByStepOneMap">
        select * from t_dept where did = #{did}
    </select>

(2)根据部门id查询部门中的所有员工

EmpMapper

public interface EmpMapper {
    /**
     * 分步查询 查询部门及其所有的员工信息
     * 第一步  查询部门信息
     * 第二步  根据查询员工信息
     */
    List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);
}

EmpMapper.xml

<!--    分步查询-->
<!--    List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);-->
    <select id="getDeptAndEmpByStepTwo" resultType="Emp">
        select * from t_emp where did = #{did}
    </select>

(3) 测试类

    @Test
    public void testGetDeptAndEmpBySteps(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        DeptMapper mapper = sqlSession.getMapper(DeptMapper.class);
        Dept dept = mapper.getDeptAndEmoByStepOne(2);
        System.out.println(dept.getDeptName());
        System.out.println("-----****************======分割线=======-----****************");
        System.out.println(dept);
    }
  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值