学习笔记——MyBatis自动映射与自定义映射;Mybatis延迟加载

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

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>

 

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6