mybatis 延迟加载

MyBatis的延迟加载(Lazy Loading)是一种优化技术,用于在需要时才加载关联对象或集合,从而提高性能和效率。以下是对MyBatis延迟加载的详细介绍:

延迟加载的基本概念

延迟加载是指在第一次访问对象的属性时才加载该对象的数据,而不是在对象创建时就立即加载所有的数据。这样可以避免不必要的数据库访问,减少系统的开销和提高性能。

xml 复制代码
<mapper namespace="com.example.UserMapper">
    <resultMap id="userMap" type="com.example.User">
        <id property="id" column="id"/>
        <result property="username" column="username"/>
        <association property="address" column="address_id" javaType="com.example.Address" fetchType="lazy">
            <id property="id" column="id"/>
            <result property="city" column="city"/>
        </association>
    </resultMap>

    <select id="selectUser" resultMap="userMap">
        SELECT * FROM user WHERE id = #{id}
    </select>
</mapper>

在上面的示例中,User类中的address属性会被设置为延迟加载。

java 复制代码
public class MyBatisExample {
    public static void main(String[] args) {
        SqlSessionFactory sqlSessionFactory = MyBatisUtil.getSqlSessionFactory();
        try (SqlSession session = sqlSessionFactory.openSession()) {
            UserMapper userMapper = session.getMapper(UserMapper.class);
            User user = userMapper.selectUser(1);
            System.out.println(user.getUsername()); // 此时不会加载address
            System.out.println(user.getAddress().getCity()); // 访问address时才会加载address
        }
    }
}


aggressiveLazyLoading属性:



相关推荐
小哇6661 小时前
MybatisPlus-JSON类型处理器 存取 数据库的JSON 字段数据
mybatis
難釋懷5 小时前
缓存同步
spring·缓存·mybatis
阿丰资源5 小时前
SpringBoot+MySQL+MyBatis-Plus+Vue前后端分离仓库管理系统 (附资料)
spring boot·mysql·mybatis
等....11 小时前
Redis使用
数据库·redis·mybatis
卓怡学长1 天前
m326数据结构课程网络学习平台的设计与实现+vue
java·spring·tomcat·maven·intellij-idea·mybatis
许杰小刀1 天前
MyBatis-Plus实战:Spring Boot数据库操作效率提升10倍
数据库·spring boot·mybatis
认真的小羽❅1 天前
从入门到精通:Spring Boot 整合 MyBatis 全攻略
spring boot·后端·mybatis
神の愛1 天前
Mybatis各个属性
数据库·oracle·mybatis
小松加哲1 天前
MyBatis完整流程详解
java·开发语言·mybatis