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



相关推荐
敲个大西瓜6 天前
mybatis拦截器插件实现数据库字段加解密
mybatis
武子康6 天前
Java-28 深入浅出 Spring 实现简易Ioc-04 在上节的业务下手动实现AOP
java·后端·mybatis
一条泥憨鱼6 天前
苍穹外卖【day6|微信登录与商品浏览功能】
后端·mybatis·苍穹外卖
vx-Biye_Design6 天前
springboot安阳地区研学旅游服务小程序-计算机毕业设计源码12785
java·vue.js·windows·spring boot·tomcat·maven·mybatis
摇滚侠6 天前
MyBatis+Spring+SpringMVC SSM 整合 179-185
java·spring·mybatis
摇滚侠6 天前
MyBatis+Spring+SpringMVC SSM ContextLoaderListener 177-178
java·spring·mybatis
Spring小子7 天前
【Spring Boot + Vue + DeepSeek】从零打造一个AI驱动的智能健康分析系统
java·spring boot·mybatis
武子康7 天前
Java-27 深入浅出 Spring - 实现简易Ioc-03 在上节的业务下手动实现IoC 从 XML 配置到 BeanFactory 反射注入
java·后端·mybatis
柏舟飞流7 天前
Spring Boot 进阶实战:整合 MyBatis、Redis、JWT,搭一个更像真实项目的后端服务
spring boot·redis·mybatis