Spring Boot 集成 MyBatis 实战详解(一)
为什么持久层开发需要 MyBatis?
早期使用 JDBC 时,开发者得手动管理连接池、编写带占位符的 SQL、绑定参数、处理结果集并在 finally 块关闭资源。这些重复的模板代码不仅效率低,还容易引发资源泄露。
MyBatis 作为优秀的持久层框架,通过简化交互、解耦 SQL 和灵活映射解决了这些问题。它让程序与数据库的交互代码量大幅减少,支持将 SQL 分离到 XML 配置中,并能自动将结果集关联到 Java 实体类。
环境搭建与核心配置
在 pom.xml 中加入 MyBatis Starter 和 MySQL 驱动即可:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
调试时建议开启 SQL 日志,这样能实时看到生成的 SQL 语句:
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
MyBatis 开发实战
注解模式
对于简单查询,注解开发更快捷。定义 Mapper 接口并添加 @Mapper 注解:
@Mapper
public interface UserInfoMapper {
// 根据 ID 查询用户
@Select("select * from user_info where id = #{id}")
UserInfo queryById(Integer id);
// 插入并返回自增主键 ID
@Insert("insert into user_info (username, password) values (#{username}, #{password})")
@Options(useGeneratedKeys = true, keyProperty = "id")
Integer insert(UserInfo userInfo);
}
XML 映射模式
遇到多表查询或动态 SQL 时,XML 是更好的选择。它能更好地管理复杂的映射关系:
<mapper namespace="com.example.demo.mapper.UserInfoXmlMapper">
<resultMap id="BaseMap" type="com.example.demo.model.UserInfo">
<id column="id" property="id"></id>
<result column="delete_flag" property="deleteFlag"></result>
</resultMap>
<select id="queryAllUser" resultMap="BaseMap">
select * from user_info
</select>
</mapper>
核心原理:#{} 与 ${} 的区别
这是面试常考点,也是安全关键。
| 特性 | #{} (预编译) | ${} (字符串替换) |
|---|---|---|
| 工作原理 | 使用 ? 占位符,提前解析优化 | 直接进行字符拼接 |
| 安全性 | 防止 SQL 注入 | 存在 SQL 注入风险 |
| 引号处理 | 自动拼接字符串引号 | 不会自动拼接引号 |
| 性能 | 高,执行计划缓存 | 较低,每次需重新解析 |
实际开发中应优先使用 #{},除非有特定需求才考虑 ${}。
多表关联查询进阶
MyBatis 的核心在于通过映射关系将联表 SQL 的结果关联到实体类,不分单表或多表。例如左连接查询:
@Select("SELECT ta.id, ta.title, tb.username FROM articleinfo ta LEFT JOIN user_info tb ON ta.uid = tb.id WHERE ta.id = #{id}")
ArticleInfo queryUserByUid(Integer id);
企业级规范与优化
- 命名规范:表名和字段名建议使用小写字母加下划线(如
user_info)。 - 驼峰转换:在配置文件中开启
map-underscore-to-camel-case: true,实现数据库字段到 Java 属性的自动映射。 - 连接池:引入 Druid 连接池以获得更强的监控功能:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-3-starter</artifactId>
<version>1.2.21</version>
</dependency>
MyBatis 通过灵活的 SQL 映射极大提升了开发效率。根据业务复杂度选择注解或 XML 模式,并始终注意 SQL 注入风险,是构建稳健持久层架构的关键。


