尧图网络 高端网站定制 · 原创设计
免费咨询热线
400-888-6620
免费获取方案
SpringBoot3整合Mybatis实战:简化Java数据访问层开发
1. SpringBoot3与Mybatis整合概述SpringBoot3作为当前Java生态中最主流的应用开发框架其简化配置和快速启动的特性深受开发者喜爱。而Mybatis作为持久层框架的经典选择凭借灵活的SQL编写方式和优秀的性能表现在企业级应用中占据重要地位。两者的整合能够充分发挥各自优势构建高效稳定的数据访问层。在实际项目中SpringBoot3与Mybatis的整合主要解决以下核心问题消除传统Mybatis配置中的大量XML文件自动化配置数据源和事务管理器简化Mapper接口的注册过程提供开箱即用的分页插件支持2. 环境准备与项目初始化2.1 开发环境要求JDK 17SpringBoot3最低要求Maven 3.6或Gradle 7.xIDE推荐IntelliJ IDEA或VS CodeMySQL 5.7/PostgreSQL等关系型数据库2.2 项目初始化配置使用Spring Initializr创建项目时需要选择以下依赖dependencies !-- SpringBoot基础依赖 -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-web/artifactId /dependency !-- Mybatis整合依赖 -- dependency groupIdorg.mybatis.spring.boot/groupId artifactIdmybatis-spring-boot-starter/artifactId version3.0.2/version /dependency !-- 数据库驱动 -- dependency groupIdcom.mysql/groupId artifactIdmysql-connector-j/artifactId scoperuntime/scope /dependency !-- 其他可选依赖 -- dependency groupIdorg.projectlombok/groupId artifactIdlombok/artifactId optionaltrue/optional /dependency /dependencies注意SpringBoot3默认使用Jakarta EE 9的命名空间与之前javax包有区别。如果项目中有老代码迁移需要特别注意包路径的变化。3. 核心配置详解3.1 数据源配置在application.yml中配置数据源spring: datasource: url: jdbc:mysql://localhost:3306/your_database?useSSLfalseserverTimezoneUTC username: root password: yourpassword driver-class-name: com.mysql.cj.jdbc.Driver hikari: pool-name: HikariCP maximum-pool-size: 20 minimum-idle: 5 idle-timeout: 30000 max-lifetime: 600000 connection-timeout: 30000 mybatis: configuration: map-underscore-to-camel-case: true default-fetch-size: 100 default-statement-timeout: 30 type-aliases-package: com.example.demo.entity mapper-locations: classpath:mapper/*.xml关键配置说明map-underscore-to-camel-case开启数据库字段下划线到Java属性驼峰的自动转换type-aliases-package指定实体类所在的包简化Mapper XML中的类型声明mapper-locations指定Mapper XML文件的位置3.2 Mybatis配置类对于需要更精细控制的场景可以创建配置类Configuration public class MybatisConfig { Bean public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { SqlSessionFactoryBean sessionFactory new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource); // 配置类型处理器 sessionFactory.setTypeHandlers(new TypeHandler[]{ new LocalDateTimeTypeHandler(), new LocalDateTypeHandler() }); // 添加插件 Interceptor[] plugins {new MybatisInterceptor()}; sessionFactory.setPlugins(plugins); return sessionFactory.getObject(); } Bean public MapperScannerConfigurer mapperScannerConfigurer() { MapperScannerConfigurer scanner new MapperScannerConfigurer(); scanner.setBasePackage(com.example.demo.mapper); return scanner; } }4. Mapper层开发实践4.1 注解方式开发对于简单的CRUD操作可以使用注解方式Mapper public interface UserMapper { Select(SELECT * FROM user WHERE id #{id}) User selectById(Param(id) Long id); Insert(INSERT INTO user(name, age) VALUES(#{name}, #{age})) Options(useGeneratedKeys true, keyProperty id) int insert(User user); Update(UPDATE user SET name#{name}, age#{age} WHERE id#{id}) int update(User user); Delete(DELETE FROM user WHERE id#{id}) int deleteById(Param(id) Long id); }4.2 XML方式开发对于复杂SQL推荐使用XML方式!-- src/main/resources/mapper/UserMapper.xml -- mapper namespacecom.example.demo.mapper.UserMapper resultMap iduserResultMap typeUser id propertyid columnid/ result propertyname columnname/ result propertyage columnage/ result propertycreateTime columncreate_time/ /resultMap select idselectByCondition resultMapuserResultMap SELECT * FROM user where if testname ! null and name ! AND name LIKE CONCAT(%, #{name}, %) /if if testminAge ! null AND age #{minAge} /if if testmaxAge ! null AND age #{maxAge} /if /where ORDER BY create_time DESC /select /mapper4.3 动态SQL技巧Mybatis提供了强大的动态SQL能力update idupdateSelective parameterTypeUser UPDATE user set if testname ! nullname#{name},/if if testage ! nullage#{age},/if /set WHERE id#{id} /update select idselectByIds resultTypeUser SELECT * FROM user WHERE id IN foreach collectionids itemid open( separator, close) #{id} /foreach /select5. 高级特性集成5.1 分页插件实现集成PageHelper实现物理分页Configuration public class PageHelperConfig { Bean public PageInterceptor pageInterceptor() { PageInterceptor pageInterceptor new PageInterceptor(); Properties properties new Properties(); properties.setProperty(helperDialect, mysql); properties.setProperty(reasonable, true); properties.setProperty(supportMethodsArguments, true); properties.setProperty(params, countcountSql); pageInterceptor.setProperties(properties); return pageInterceptor; } } // 使用示例 public PageInfoUser listUsers(int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); ListUser users userMapper.selectAll(); return new PageInfo(users); }5.2 多数据源配置对于需要连接多个数据库的场景Configuration MapperScan(basePackages com.example.primary.mapper, sqlSessionFactoryRef primarySqlSessionFactory) public class PrimaryDataSourceConfig { Bean ConfigurationProperties(spring.datasource.primary) public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } Bean public SqlSessionFactory primarySqlSessionFactory( Qualifier(primaryDataSource) DataSource dataSource) throws Exception { SqlSessionFactoryBean sessionFactory new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource); return sessionFactory.getObject(); } Bean public DataSourceTransactionManager primaryTransactionManager( Qualifier(primaryDataSource) DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } }5.3 二级缓存配置启用Mybatis二级缓存提升性能!-- 在Mapper XML中 -- cache evictionLRU flushInterval60000 size512 readOnlytrue/ !-- 全局配置 -- mybatis: configuration: cache-enabled: true6. 常见问题与解决方案6.1 启动时Mapper接口报错问题现象启动时报Invalid bound statement (not found)错误解决方案检查MapperScan或Mapper注解是否正确配置确认Mapper XML文件路径与mybatis.mapper-locations配置匹配检查XML中的namespace是否与Mapper接口全限定名一致6.2 事务不生效问题问题现象方法添加Transactional后事务不回滚排查步骤确认使用的是org.springframework.transaction.annotation.Transactional检查方法是否为public且未被final修饰确认异常类型是否被捕获未抛出检查是否在同一个类中方法调用导致AOP失效6.3 性能优化建议批量操作使用foreach标签或SqlSession的批量方法Autowired private SqlSessionTemplate sqlSessionTemplate; public void batchInsert(ListUser users) { SqlSession session sqlSessionTemplate.getSqlSessionFactory() .openSession(ExecutorType.BATCH, false); try { UserMapper mapper session.getMapper(UserMapper.class); for (User user : users) { mapper.insert(user); } session.commit(); } finally { session.close(); } }延迟加载对于关联查询配置lazyLoadingEnabledtruemybatis: configuration: lazy-loading-enabled: true aggressive-lazy-loading: falseSQL优化使用sql片段复用SQL语句sql idbaseColumn id, name, age, create_time /sql select idselectAll resultMapuserResultMap SELECT include refidbaseColumn/ FROM user /select7. 最佳实践总结经过多个项目的实践验证以下配置组合表现最佳连接池配置HikariCP 合理的连接数设置spring: datasource: hikari: maximum-pool-size: ${DB_MAX_POOL_SIZE:20} minimum-idle: ${DB_MIN_IDLE:5} idle-timeout: 30000 max-lifetime: 1800000 connection-timeout: 5000Mybatis配置mybatis: configuration: default-statement-timeout: 30 map-underscore-to-camel-case: true cache-enabled: true lazy-loading-enabled: true multiple-result-sets-enabled: true use-column-label: true日志配置开发环境开启SQL日志logging: level: com.example.demo.mapper: debug监控建议集成Micrometer监控SQL性能Bean public MetricsCollector metricsCollector() { return new MetricsCollector(hikariDataSource); }在实际开发中建议根据项目规模选择合适的整合方式。小型项目可以使用纯注解方式简化开发中大型项目推荐XML方式管理复杂SQL。对于需要高度定制化的场景可以通过自定义TypeHandler和Interceptor扩展Mybatis功能。
RELATED

相关推荐

SadTalker 安装部署指南:macOS / Windows / WSL / Docker 多平台环境搭建实战

SadTalker 安装部署指南:macOS / Windows / WSL / Docker 多平台环境搭建实战

SadTalker 安装部署指南:macOS / Windows / WSL / Docker 多平台环境搭建实战 【免费下载链接】SadTalker [CVPR 2023] SadTalker:Learning Realistic 3D Motion Coefficients for Stylized Audio-Driven Single Image Talking Face Animation 项目地址…

📅 2026/9/14 17:58:15
Python开发Discord机器人:从入门到实践

Python开发Discord机器人:从入门到实践

1. 项目概述 Discord作为全球最流行的即时通讯平台之一,其机器人生态已经发展成为一个庞大的开发者社区。根据Discord官方数据,目前平台上有超过300万个活跃的机器人,每天处理数十亿条消息。使用Python开发Discord机器人之所以成为主流选择&…

📅 2026/9/14 17:58:15
Hindsight Supabase 租户扩展深度解析:本地 JWKS 验证、按用户 Schema 隔离与内置版本迁移

Hindsight Supabase 租户扩展深度解析:本地 JWKS 验证、按用户 Schema 隔离与内置版本迁移

Hindsight Supabase 租户扩展深度解析:本地 JWKS 验证、按用户 Schema 隔离与内置版本迁移 【免费下载链接】hindsight Hindsight: Agent Memory That Learns 项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight 本篇指南聚焦 Hindsight 仓…

📅 2026/9/14 17:53:15
MORE NEWS

更多资讯

📰

OpenClaw实战:AI Agent手写爬虫抓取GitHub releases的踩坑与方案

2026 年 3 月 28 日,我在做 OpenClaw 的一次例行升级时,被一个看似简单的需求卡了整整半天:让 AI 自己去 GitHub 拿一份 release 清单和 skill 仓库说明。折腾到最后,连 OpenClaw 里的 AI Agent 都被逼无奈,放弃了内置…

📰

Matlab读取Excel数据与分类标签处理实战

1. 项目概述:Excel数据读取与分类标签处理刚接手一个数据分析项目时,最基础也最关键的一步就是数据读取。很多新手会卡在这个看似简单的环节,特别是当数据格式和结构有特定要求时。今天我们就来彻底解决这个问题——如何在Matlab中正确读取Ex…

📰

SpringBoot3整合Mybatis实战:简化Java数据访问层开发

1. SpringBoot3与Mybatis整合概述 SpringBoot3作为当前Java生态中最主流的应用开发框架,其简化配置和快速启动的特性深受开发者喜爱。而Mybatis作为持久层框架的经典选择,凭借灵活的SQL编写方式和优秀的性能表现,在企业级应用中占据重要地位。…

📰

SadTalker 安装部署指南:macOS / Windows / WSL / Docker 多平台环境搭建实战

SadTalker 安装部署指南:macOS / Windows / WSL / Docker 多平台环境搭建实战 【免费下载链接】SadTalker [CVPR 2023] SadTalker:Learning Realistic 3D Motion Coefficients for Stylized Audio-Driven Single Image Talking Face Animation 项目地址…

📰

Python开发Discord机器人:从入门到实践

1. 项目概述 Discord作为全球最流行的即时通讯平台之一,其机器人生态已经发展成为一个庞大的开发者社区。根据Discord官方数据,目前平台上有超过300万个活跃的机器人,每天处理数十亿条消息。使用Python开发Discord机器人之所以成为主流选择&…

📰

Hindsight Supabase 租户扩展深度解析:本地 JWKS 验证、按用户 Schema 隔离与内置版本迁移

Hindsight Supabase 租户扩展深度解析:本地 JWKS 验证、按用户 Schema 隔离与内置版本迁移 【免费下载链接】hindsight Hindsight: Agent Memory That Learns 项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight 本篇指南聚焦 Hindsight 仓…

TODAY

今日更新

THIS WEEK

本周精选

THIS MONTH

本月热门

读完文章,想聊聊您的网站?

告诉我们您的行业与需求,资深顾问一对一梳理方案与报价,全程免费。

📞 💬