设为首页 加入收藏

TOP

学习笔记——MyBatis自动映射与自定义映射;Mybatis延迟加载
2023-07-25 21:41:51 】 浏览:45
Tags:习笔记 MyBatis Mybatis 加载

2023-01-10

 一、MyBatis自动映射与自定义映射

1、自动映射:

在映射文件中使用的是“resultType”。指的是自动将数据库中表的字段与类中的属性进行关联映射。

2、自定义映射:

(1)在映射文件中使用的是“resultMap”。一般是自动映射解决不了的问题,就使用自定义映射。

有“多表连接查询,需要返回多张表的结果集”、以及“单表查询时,不支持驼峰式自动映射(这时一般使用别名)”

例如:在映射文件中的实例代码,之后在<select>中设置为“resultMap”

    <resultMap id="empAndDeptResultMap" type="employee">
<!--        定义主键-->
        <id column="id" property="id"></id>
<!--        定义非主键,column里面放置数据库中的字段,property中放置类中的属性-->
        <result column="last_name" property="lastName"></result>
        <result column="email" property="email"></result>
        <result column="salary" property="salary"></result>
        <result column="dept_id" property="dept.deptId"></result>
        <result column="dept_name" property="dept.deptName"></result>
    </resultMap>

(2)association

<resultMap id="selectEmplAndDeptByIdAssociation" type="employee">
        <!--        定义主键-->
        <id column="id" property="id"></id>
        <!--        定义非主键,column里面放置数据库中的字段,property中放置类中的属性-->
        <result column="last_name" property="lastName"></result>
        <result column="email" property="email"></result>
        <result column="salary" property="salary"></result>
        <association property="dept"
                     javaType="com.hh.mybatis.pojo.Dept">
            <result column="dept_id" property="deptId"></result>
            <result column="dept_name" property="deptName"></result>
        </association>

</resultMap>

(3)分步查询

使用多表连接查询,改为“分步单表查询”,从而提高程序运行效率

3、注意:自动映射(resultType)与自定义映射(resultMap)只能同时使用一个。

二、Mybatis延迟加载

即需要时加载,不需要时暂时不加载

好处是:能提升程序运行效率

延迟加载在“mybatis-config.xml”中<setting>的设置

    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
<!--        延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
<!--        延迟加载的属性-->
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇LeetCode刷题第八九十周 下一篇SpringBoot+Mybatis-plus整合easy..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目