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>
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。