延迟加载

在进行数据查询时,为了提高数据库查询性能,尽量使用单表查询,因为单表查询比多表关联查询速度要快。

如果查询单表就可以满足需求,一开始先查询单表,当需要关联信息时,再关联查询,当需要关联信息再查询这个叫延迟加载

延迟加载:在真正使用数据的时候才发起查询,不用的时候不查询关联的数据,延迟加载又叫按需查询(懒加载)

  • 延迟加载的条件:resultMap可以实现高级映射(使用association、collection实现一对一及一对多映射),association、collection具备延迟加载功能。

    • association、collection标签属性:colunm 关联两张表的列名;select 要延迟加载的statement的id,即命名空间.SQL执行的id

  • 延迟加载的好处: 先从单表查询、需要时再从关联表去关联查询,大大提高 数据库性能,因为查询单表要比关联查询多张表速度要快。

  • 延迟加载的实例: 如果查询订单并且关联查询用户信息。如果先查询订单信息即可满足要求,当我们需要查询用户信息时再查询用户信息。把对用户信息的按需去查询就是延迟加载

立即加载:不管用不用,只要一调用方法,马上发起查询。

在Mybatis的xml配置文件中配置全局延迟加载

    <settings>
        <!--开启全局的懒加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!--关闭立即加载,其实不用配置,默认为false-->
        <setting name="aggressiveLazyLoading" value="false"/>
        <!--开启Mybatis的sql执行相关信息打印-->
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>

两个POJO

@Data
public class Animal {
    private int id;
    private String category;
    private List<Dog> elements;
}
@Data
public class Dog {
    private int id;
    private String name;
}

两个Mapper接口

public interface AnimalMapper {
    List<Dog> findAll() throws Exception;
}

public interface DogMapper {
    Dog findById(Integer r_id) throws Exception;
}

两个Mapper.xml映射文件

<mapper namespace="mybatis_test.AnimalMapper">
    <resultMap id="animalMap" type="mybatis_test.Animal">
        <id property="id" column="id"/>
        <result property="category" column="category"/>
<!-- select:要延迟加载的statement的id , colunm:关联两张表的那个列的列名  -->
        <collection property="elements" ofType="mybatis_test.Dog"
                    column="r_id" select="mybatis_test.DogMapper.findById"/>
    </resultMap><select id="findAll" resultMap="animalMap">
        select * from animal;
    </select>
</mapper><mapper namespace="mybatis_test.DogMapper">
    <resultMap id="DogMap" type="mybatis_test.Dog">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
    </resultMap><select id="findById" resultMap="DogMap">
        select * from Dog where r_id=#{r_id};
    </select>
</mapper>

当只是获取animal对象时,不会去查dog表;当需要获取animal对象中的List<Dog>属性时,才会去查dog表

 

原文地址:https://www.cnblogs.com/yjh1995/p/13893782.html