news 2026/8/3 15:12:26

MyBatis延迟加载、缓存机制与注解开发

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
MyBatis延迟加载、缓存机制与注解开发

一、延迟加载策略


1.1 延迟加载的概念


立即加载:查询用户时,默认也把该用户的所有账户信息查询出来

延迟加载:查询用户时,不查询账户信息,等需要使用账户数据时才去查询

1.2 应用场景


查询账户(多对一)时,可以直接查询用户信息 → 立即加载

查询用户(一对多)时,可以先不查账户信息 → 延迟加载

1.3 多对一延迟加载配置


在 SqlMapConfig.xml 中开启延迟加载:

<settings> <!-- 开启延迟加载 --> <setting name="lazyLoadingEnabled" value="true"/> <!-- 将积极加载改为按需加载 --> <setting name="aggressiveLazyLoading" value="false"/> </settings>


AccountMapper.xml 配置:

<resultMap id="accountMap" type="Account"> <result property="id" column="id"/> <result property="uid" column="uid"/> <result property="money" column="money"/> <association property="user" javaType="User" select="com.qcbyjy.mapper.UserMapper.findById" column="uid"/> </resultMap> <select id="findAll" resultMap="accountMap"> SELECT * from account </select>


二、MyBatis缓存机制


2.1 一级缓存(SqlSession缓存)


一级缓存是 SqlSession 级别的缓存,底层使用Map集合存储:

key:执行的SQL语句

value:查询的结果对象

一级缓存的生命周期与SqlSession相同。以下操作会清空一级缓存:

session.clearCache()

session.update()、insert()、delete()、commit()、close()

@Test public void testFindById() { User user = mapper.findById(41); System.out.println(user); // 第二次查询会从缓存中获取,不会查询数据库 User user2 = mapper.findById(41); System.out.println(user2); }



三、注解开发


3.1 单表CRUD注解


在 SqlMapConfig.xml 中配置Mapper接口所在的包:

<mappers> <package name="com.qcbyjy.mapper"/> </mappers>


UserMapper接口:

public interface UserMapper { @Select("select * from user") @Results(id="userMap", value={ @Result(id=true, column="id", property="id"), @Result(column="username", property="username"), @Result(column="birthday", property="birthday"), @Result(column="sex", property="sex"), @Result(column="address", property="address") }) public List<User> findAll(); @Select("select * from user where id = #{uid}") @ResultMap("userMap") public User findById(Integer uid); @Insert("insert into user (username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address})") public void insert(User user); @Update("update user set username = #{username},birthday=#{birthday},sex=#{sex},address=#{address} where id = #{id}") public void update(User user); @Delete("delete from user where id = #{id}") public void delete(Integer userId); @Select("select count(*) from user") public Integer findByCount(); @Select("select * from user where username like #{username}") public List<User> findByUsername(String username); }



3.2 多对一注解查询(延迟加载)

public interface AccountMapper { @Select("select * from account") @Results(value={ @Result(id=true, column="aid", property="id"), @Result(column="uid", property="uid"), @Result(column="money", property="money"), @Result(property="user", javaType=User.class, column="uid", one=@One(select="com.qcbyjy.mapper.UserMapper.findById", fetchType=FetchType.LAZY)) }) public List<Account> findAll(); }



3.3 一对多注解查询(延迟加载)

public interface UserMapper { @Select("select * from user") @Results(id="userMap", value={ @Result(id=true, column="id", property="id"), @Result(column="username", property="username"), @Result(column="birthday", property="birthday"), @Result(column="sex", property="sex"), @Result(column="address", property="address"), @Result(property="accounts", column="id", many=@Many(select="com.qcbyjy.mapper.AccountMapper.findByUid", fetchType=FetchType.LAZY)) }) public List<User> findAll(); } public interface AccountMapper { @Select("select * from account where uid = #{uid}") public List<Account> findByUid(Integer uid); }


四、总结

特性XML方式注解方式
简单语句支持支持,更简洁
复杂语句支持较复杂
动态SQL支持良好支持但较繁琐
可读性较高高(简单语句)
推荐场景复杂SQL、动态SQL简单SQL、Spring Boot项目


实际开发建议:简单SQL可以使用注解方式,复杂SQL和动态SQL建议使用XML方式-。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/8/3 15:10:46

Python图形界面(GUI)Tkinter笔记(三十一):PanedWindow动态界面布局设计容器控件

PanedWindow组件是为动态界面布局设计的容器控件。其核心功能体现在以下三个方面: 1. 动态分区管理: 通过水平(orient=HORIZONTAL)或垂直(VERTICAL)分割线创建可交互调整的窗格区域。用户可直接拖动分隔条实时修改各分区尺寸,支持嵌套布局(如垂直分割窗格内再嵌套水平分割窗格…

作者头像 李华
网站建设 2026/8/3 15:05:55

电力系统同步相量测量算法优化与工程实践

1. 电力系统同步相量计算的核心价值 在电力系统运行与控制中&#xff0c;同步相量测量是状态估计、故障检测和稳定控制的基础。传统方法面临非稳态信号分析精度不足的问题&#xff0c;这直接影响了电网动态响应的判断准确性。我参与过多个省级电网的PMU&#xff08;同步相量测量…

作者头像 李华
网站建设 2026/8/3 15:05:40

Path of Building终极指南:5分钟轻松驾驭流放之路离线构筑神器

Path of Building终极指南&#xff1a;5分钟轻松驾驭流放之路离线构筑神器 【免费下载链接】PathOfBuilding Offline build planner for Path of Exile. 项目地址: https://gitcode.com/gh_mirrors/pat/PathOfBuilding 还在为《流放之路》复杂的角色构建而烦恼吗&#x…

作者头像 李华
网站建设 2026/8/3 15:01:56

Windows右键菜单终极优化指南:3步打造高效工作环境

Windows右键菜单终极优化指南&#xff1a;3步打造高效工作环境 【免费下载链接】ContextMenuManager &#x1f5b1;️ 纯粹的Windows右键菜单管理程序 项目地址: https://gitcode.com/gh_mirrors/co/ContextMenuManager 还在为Windows右键菜单越来越臃肿而烦恼吗&#x…

作者头像 李华
网站建设 2026/8/3 14:59:49

Ohook终极指南:免费解锁完整Office功能的全新解决方案

Ohook终极指南&#xff1a;免费解锁完整Office功能的全新解决方案 【免费下载链接】ohook An universal Office "activation" hook with main focus of enabling full functionality of subscription editions 项目地址: https://gitcode.com/gh_mirrors/oh/ohook …

作者头像 李华
网站建设 2026/8/3 14:59:47

如何彻底解锁Wand专业版功能:告别2小时限制的终极解决方案

如何彻底解锁Wand专业版功能&#xff1a;告别2小时限制的终极解决方案 【免费下载链接】Wand-Enhancer Advanced UX and interoperability extension for Wand (WeMod) app 项目地址: https://gitcode.com/GitHub_Trending/we/Wand-Enhancer 你是否厌倦了Wand&#xff0…

作者头像 李华