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属性:



相关推荐
chxii2 分钟前
在 Spring Boot 中,MyBatis 的“自动提交”行为解析
java·数据库·mybatis
有一个好名字11 小时前
MyBatis-Plus 三种数据库操作方式详解 + 常用方法大全
数据库·mybatis
颜如玉16 小时前
动态拼接SQL实践备忘📝
java·sql·mybatis
朝新_1 天前
【实战】博客系统:项目公共模块 + 博客列表的实现
数据库·笔记·sql·mybatis·交互·javaee
小小哭包1 天前
Spring Boot整合多个MyBatis数据源实战教程
spring boot·后端·mybatis
b***9102 天前
【SpringBoot3】Spring Boot 3.0 集成 Mybatis Plus
android·前端·后端·mybatis
小杍随笔2 天前
【基于 Spring Boot 3 + Spring Security + MyBatis-Plus 构建的用户登录功能】
spring boot·spring·mybatis
♡喜欢做梦2 天前
MyBatis操作数据库(入门)
java·数据库·mybatis
ArabySide2 天前
【Spring Boot】基于MyBatis的条件分页
java·spring boot·后端·mybatis
百***61872 天前
springboot整合mybatis-plus(保姆教学) 及搭建项目
spring boot·后端·mybatis