MyBatis笔记(四)——懒加载

   在数据库查询记录过程中,单表查询要比多表查询来得效率更加高,单表查询的使用会提高数据库的性能。

   在映射文件中,我们可以自定义映射类型,即resultmap,在其中,能够做到一对多(collection),一对一(association)的高级映射效果,而collectionassociation具有懒加载的功能。

   例子

  住房信息与户主信息,相关部门需要查询住房信息,当需要查询户主信息的时候,再查询户主信息。

    <resultMap id="houseAndhost" type="House">
        <id column="id" property="id"/>
        <result column="address" property="address"/>
        <!--property为House中的属性
            如果select在其他Mapper中,需要加上前缀
            column为查询时需要用到的House表中的列-->
        <association property="host" javaType="Host" column="hid" select="findHostById"/>
    </resultMap>

    <!-- 返回自定义的映射,需要写resultMap而不是resultType-->
    <select id="findHouseAndHostLazyLoading" resultMap="houseAndhost">
        SELECT * from house
    </select>

    <select id="findHostById" resultType="Host">
        select * from host where hid = #{hid}
    </select>

 在懒加载中,asscociation会使用select与column,而在非懒加载中,asscociation标签下会直接进行查询。

  测试

 调用该mapper中的懒加载方法得到住房,需要使用户主信息时,再查询之。

  这里我们需要配置延迟加载的设置,在mybatis中,延迟加载是默认取消的。

  在sqlMapperConfig.xml中配置

 <settings>
        <!-- 打开延迟加载 的开关 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!-- 将积极加载改为消极加载即按需要加载 -->
        <setting name="aggressiveLazyLoading" value="false"/>
        <!-- 开启二级缓存 -->
        <!-- <setting name="cacheEnabled" value="true"/>-->
    </settings>

猜你喜欢

转载自blog.csdn.net/lpckr94/article/details/80280970