欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 旅游 > mybatis 延迟加载

mybatis 延迟加载

2024/10/24 10:20:16 来源:https://blog.csdn.net/weixin_47503016/article/details/140292376  浏览:    关键词:mybatis 延迟加载

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

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

<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属性会被设置为延迟加载。

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()); // 此时不会加载addressSystem.out.println(user.getAddress().getCity()); // 访问address时才会加载address}}
}

在这里插入图片描述
aggressiveLazyLoading属性:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com