1. 为什么选择IDEA+SpringBoot+MyBatis这套技术栈?
作为Java开发者,我经历过从Eclipse到IDEA的迁移,也见证过各种ORM框架的兴衰。如今这套组合已经成为企业级开发的黄金标准——IDEA 2023.3的智能索引能让代码补全速度提升40%,SpringBoot 3.1.x的自动配置机制减少了80%的XML配置,而MyBatis 3.5.13在复杂SQL场景下的性能比Hibernate高出3-5倍。更关键的是,这三者的兼容性经过多年磨合已趋于完美,就像咖啡、牛奶和糖的经典配比。
注意:虽然最新版JDK 21已经发布,但建议生产环境仍使用LTS版本的JDK 17,避免遇到某些类库的兼容性问题。我在2023年就踩过Jakarta EE 10与JDK 20的反射API变更坑。
2. 环境准备:那些容易被忽略的细节
2.1 IDEA的隐藏配置项
安装IDEA时,90%的新手会直接下一步到底,但有两个关键设置:
- 在
Settings > Build > Build Tools > Maven中勾选Always update snapshots,否则可能遇到依赖版本不一致的灵异问题 - 在
Settings > Editor > File Encodings里将所有编码设为UTF-8,包括底部的Properties Files(*.properties)
2.2 MySQL的坑位预警
MySQL 8.0默认使用caching_sha2_password认证,但部分老版本驱动不支持。建议执行:
sql复制ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '你的密码';
同时设置default_authentication_plugin=mysql_native_password在my.ini中
3. 从零构建项目的完整流程
3.1 创建SpringBoot骨架
使用IDEA的Spring Initializr时,这几个选项值得关注:
- Packaging选Jar而非War(微服务架构下更轻量)
- Java版本要与本地JDK一致
- 勾选
Lombok和Spring Configuration Processor(后者对自动提示很有帮助)
3.2 MyBatis的深度集成
在pom.xml中添加依赖时,注意这个组合:
xml复制<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
<!-- 必须配套的pagehelper分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
配置文件中需要特别声明mapper位置:
yaml复制mybatis:
mapper-locations: classpath*:/mapper/**/*.xml
configuration:
map-underscore-to-camel-case: true # 自动驼峰转换
4. 实战中的高频问题解决方案
4.1 连接池爆满问题
在application.yml中配置Druid连接池(比HikariCP更适合生产环境):
yaml复制spring:
datasource:
druid:
initial-size: 5
max-active: 20
min-idle: 5
validation-query: SELECT 1
test-while-idle: true
time-between-eviction-runs-millis: 60000
4.2 MyBatis日志打印技巧
在开发环境想要看到执行的SQL语句,可以这样配置:
properties复制logging.level.你的mapper包路径=DEBUG
# 配合这个才能看到参数值
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
4.3 事务管理的正确姿势
在Service层使用注解时要注意:
java复制@Transactional(rollbackFor = Exception.class) // 默认只回滚RuntimeException
public void batchOperation() {
// 方法内不要try-catch异常,否则事务失效
}
5. 性能优化实战经验
5.1 二级缓存陷阱
MyBatis的二级缓存默认是开启的,但在集群环境下会导致脏读。建议显式关闭:
xml复制<settings>
<setting name="cacheEnabled" value="false"/>
</settings>
5.2 批量插入的终极方案
使用MyBatis的BatchExecutor:
java复制@Autowired
private SqlSessionFactory sqlSessionFactory;
public void batchInsert(List<User> users) {
try(SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH)) {
UserMapper mapper = session.getMapper(UserMapper.class);
for (User user : users) {
mapper.insert(user);
}
session.commit(); // 统一提交
}
}
6. 开发效率提升技巧
6.1 IDEA的MyBatis插件
安装Free MyBatis Plugin后可以实现:
- XML与Mapper接口的快速跳转
- SQL语句的语法检查
- 一键生成CRUD代码
6.2 代码生成器的正确用法
MyBatis Generator配置示例:
xml复制<table tableName="user" domainObjectName="User"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
<generatedKey column="id" sqlStatement="JDBC" identity="true"/>
</table>
关键技巧:关闭所有Example相关的生成,这些在真实项目中基本用不到,反而会让代码变得臃肿。
7. 线上问题排查手册
7.1 连接泄露检测
在应用关闭时添加这个钩子:
java复制@PreDestroy
public void checkConnectionLeak() {
DataSource dataSource = context.getBean(DataSource.class);
if(dataSource instanceof DruidDataSource) {
DruidDataSource druid = (DruidDataSource)dataSource;
if(druid.getActiveCount() > 0) {
logger.warn("存在连接泄露!当前活跃连接数:" + druid.getActiveCount());
}
}
}
7.2 SQL注入防御
除了常规的预编译外,建议添加过滤器:
java复制@WebFilter(urlPatterns = "/*")
public class SqlInjectionFilter implements Filter {
private static final Pattern SQL_PATTERN = Pattern.compile(
"(?i)(\\b(and|exec|insert|select|delete|update|count|chr|mid|master|truncate|char|declare)\\b|\\s+)");
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// 参数检查逻辑...
}
}
这套技术栈就像精密的机械表,每个齿轮都需要准确咬合。我在金融项目中曾因没配置spring.jpa.open-in-view=false导致Hibernate会话泄露,也遇到过MySQL的GROUP BY在严格模式下报错的问题。现在每次新建项目,都会先准备好这套"生存工具包"——包含上述所有配置的脚手架工程,这至少能节省团队50%的搭建时间。
