MyBatis 是 Java 生态里最经典的持久层框架之一,它通过 Mapper 接口加 XML(或注解)把 Java 对象和 SQL 语句绑定起来,让开发者不用写重复的 JDBC 样板代码。绝大多数人上手时卡住的地方就两个:参数绑定报错(比如 invalid property 或找不到参数名)、结果映射对不上(查出来的对象字段全是 null 或类型不对)。这两个问题的根源其实高度集中——参数名没对齐、#{} 和 ${} 用混、resultType 和数据库列名没对上。本文从环境搭建讲起,把 Mapper 接口、参数绑定、结果映射、动态 SQL 一次讲透,照着敲就能跑通。
MyBatis 和 JDBC、Hibernate 到底有什么区别
在动手之前先搞清楚定位,否则容易用错场景。
MyBatis 是指半自动化的持久层框架:SQL 需要自己写,框架负责把参数填进 PreparedStatement、把结果集回填成 Java 对象。对比一下:
| 维度 | 原生 JDBC | MyBatis | Hibernate/JPA |
|---|---|---|---|
| SQL 编写 | 全部手写拼接 | 手写,框架做参数绑定和映射 | 自动生成( Criteria/ JPQL) |
| 学习成本 | 低但繁琐 | 中等 | 较高 |
| SQL 可控性 | 完全可控 | 完全可控 | 弱,复杂查询费劲 |
| 适合场景 | 学习原理 | 复杂查询多、需精细优化 SQL | 表结构稳定、CRUD 为主 |
一句话结论:SQL 复杂、需要精细控制查询性能的项目,MyBatis 是性价比最高的选择;如果你希望框架自动生成全部 SQL,Hibernate 更合适,而 MyBatis-Plus 则是 MyBatis 的增强版,兼顾了两者优点。
5 分钟搭好环境:依赖、配置、SqlSessionFactory
Maven 依赖怎么写
以 MyBatis 3.5.x 加 MySQL 8 为例,pom.xml 里加这两块:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.16</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.4.0</version>
</dependency>
解释一下:mybatis 是核心 jar,版本 3.5.16 是目前长期维护的稳定线;驱动用 8.x 版本对应 MySQL 8,如果你连的是 MySQL 5.x,把 groupId 换成 mysql、artifactId 换成 mysql-connector-java 即可。
配置文件 mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="dev">
<environment id="dev">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=Asia/Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/BlogMapper.xml"/>
</mappers>
</configuration>
逐段解释:transactionManager type="JDBC" 表示事务交给 JDBC 原生管理(生产环境建议换成 Spring 管理);dataSource type="POOLED" 是 MyBatis 内置的连接池,省得自己再引 Druid/Hikari;mappers 节点注册 Mapper XML,注意路径是相对 classpath 的。数据库里先建好 blog 表(id、title、author、create_time 四列)再往下走。
启动入口:拿到 SqlSessionFactory
public class App {
public static void main(String[] args) throws IOException {
try (Reader reader = Resources.getResourceAsReader("mybatis-config.xml")) {
SqlSessionFactory factory =
new SqlSessionFactoryBuilder().build(reader);
try (SqlSession session = factory.openSession()) {
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlogById(1L);
System.out.println(blog);
}
}
}
}
关键点:SqlSessionFactory 是重量级对象,整个应用只建一次;SqlSession 是轻量的,必须用完关闭(上面用 try-with-resources 自动关);session.getMapper() 把接口和 XML 绑定,这是 MyBatis 动态代理的核心——接口里不写实现类,MyBatis 在运行时生成代理对象。
Mapper 接口怎么写:XML 映射和注解映射
先定义实体类和接口:
public class Blog {
private Long id;
private String title;
private String author;
private Date createTime;
// getter/setter 省略
}
public interface BlogMapper {
Blog selectBlogById(Long id);
List<Blog> selectBlogsByCondition(Blog query);
int insertBlog(Blog blog);
}
再写对应的 XML(放在 resources/mapper/BlogMapper.xml,命名空间和接口全限定名必须一致):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.BlogMapper">
<select id="selectBlogById" resultType="com.example.entity.Blog">
SELECT id, title, author, create_time
FROM blog WHERE id = #{id}
</select>
<insert id="insertBlog" parameterType="com.example.entity.Blog"
useGeneratedKeys="true" keyProperty="id">
INSERT INTO blog (title, author, create_time)
VALUES (#{title}, #{author}, #{createTime})
</insert>
</mapper>
解释几个容易踩的点:namespace 必须等于接口的全限定名,否则 getMapper 找不到映射;id 必须和接口方法名完全一致;resultType 是查询结果自动映射的目标类型;useGeneratedKeys="true" keyProperty="id" 让插入后自增主键回填到对象里,插入完再取 blog.getId() 就有值了。注解方式(@Select("SELECT ... WHERE id = #{id}"))适合简单语句,复杂动态 SQL 还是 XML 更清晰,大多数项目会混用。
参数绑定为什么总出错:#{} 和 ${} 到底怎么选
这是报错重灾区,先给结论:日常 99% 的场景用 #{},只有拼表名、排序字段这类标识符才用 ${}。
#{} 会被替换成 ? 占位符,走 PreparedStatement 预编译,参数类型安全、天然防 SQL 注入;${} 是直接做字符串替换,拼进 SQL 原文,有注入风险。传用户输入的等值查询、模糊查询、范围条件,一律 #{}。
单参数:名字随意
<select id="selectBlogById" resultType="com.example.entity.Blog">
SELECT * FROM blog WHERE id = #{id}
</select>
只有一个参数时,XML 里 #{ 后面写什么都行(#{id}、#{anything} 等价),因为 MyBatis 会把唯一参数原样传入。
多参数:两种写法对比
写法一:@Param 显式命名(推荐)
Blog selectBlogByKeyword(@Param("kw") String keyword, @Param("limit") int limit);
SELECT * FROM blog WHERE title LIKE CONCAT('%', #{kw}, '%') LIMIT #{limit}
写法二:Map 或对象传参
Blog selectBlogByMap(Map<String, Object> params);
SELECT * FROM blog WHERE id = #{id} AND author = #{author}
对应 Map 里必须真的放 id、author 两个 key。
最容易踩的坑:不加 @Param 的多参数
Blog selectBlog(Long id, String author); // 没加 @Param
此时 XML 里只能写 #{param1}、#{param2}(按形参顺序),写 #{id} 直接抛 BindingException: Invalid property 'id'。这就是“参数绑定老出错”最常见的两个原因:要么漏了 @Param,要么参数名和 XML 里的 #{xxx} 对不上。记住一条规则:XML 里 #{后面的名字,必须能在参数上下文里找到。
结果映射对不上:resultType 和 resultMap 一次讲清
查出来对象字段全是 null,九成是列名和属性名没对上。
自动映射:mapUnderscoreToCamelCase
MyBatis 默认按列名精确匹配属性名,数据库的 create_time 不会自动匹配 Java 的 createTime。全局开启驼峰转换:
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
配好后 create_time 自动映射到 createTime,简单查询基本不用手写映射。注意这个设置只对”列名等于属性名下划线版本”的情况有效,别名、嵌套查询不适用。
手动映射:resultMap
列名和属性名对不上(比如 SQL 里 SELECT author AS writer)、或者要处理一对一、一对多关联时,用 resultMap:
<resultMap id="blogMap" type="com.example.entity.Blog">
<id property="id" column="id"/>
<result property="title" column="title"/>
<result property="author" column="writer"/>
<result property="createTime" column="create_time"/>
</resultMap>
<select id="selectBlogById" resultMap="blogMap">
SELECT id, title, author AS writer, create_time
FROM blog WHERE id = #{id}
</select>
<id> 标签标记主键,MyBatis 靠它做结果去重和缓存判断,一对一关联查询里必须写。association 处理一对一,collection 处理一对多嵌套查询,这里不展开,但记住:结果映射对不上时,先检查三件事——resultType/resultMap 引用对不对、column 名拼写对不对、属性类型和表字段类型兼容不兼容(比如表里是 bigint 却映射成 Integer,大数据量下会溢出报错)。
动态 SQL 实战:if、where、foreach 怎么写
条件查询:if 加 where
<select id="selectBlogsByCondition" resultMap="blogMap">
SELECT id, title, author AS writer, create_time
FROM blog
<where>
<if test="title != null and title != ''">
AND title LIKE CONCAT('%', #{title}, '%')
</if>
<if test="author != null and author != ''">
AND author = #{author}
</if>
</where>
ORDER BY id DESC
</select>
<where> 标签会自动处理第一个条件前多余的 AND/OR,并且在所有条件都不满足时整段不生成。注意 test 里的字符串判断要写 != '',否则空串也会进条件。调用时传一个 Blog query 对象,没赋值的字段自动跳过。
批量插入:foreach
<insert id="insertBatch">
INSERT INTO blog (title, author, create_time)
VALUES
<foreach collection="list" item="item" separator=",">
(#{item.title}, #{item.author}, #{item.createTime})
</foreach>
</insert>
对应接口写 int insertBatch(@Param("list") List<Blog> blogs);,separator="," 让每组括号用逗号连接。批量条数多的话(经验上超过 500 条)建议分批提交,否则 SQL 过长可能触发 MySQL 的 max_allowed_packet 限制。
复用片段:sql 加 include
<sql id="blogColumns">id, title, author AS writer, create_time</sql>
<select id="selectBlogById" resultMap="blogMap">
SELECT <include refid="blogColumns"/> FROM blog WHERE id = #{id}
</select>
列多时抽成 <sql> 片段,避免每个语句重复写、改列名要改十几处。
常见问题
#{} 和 ${} 有什么区别?
#{} 预编译占位符(变成 ?),防注入,是默认选择;${} 字符串直接替换,有注入风险,只用于表名、列名、排序字段这类无法预编译的标识符。
多参数时报 BindingException 怎么解决?
检查 XML 里 #{xxx} 的名字:接口参数没加 @Param 时只能用 param1、param2;加了 @Param("kw") 就必须写 #{kw}。参数名和占位符对不上是这个异常的唯一原因。
查询结果字段全是 null 怎么办?
先确认 SQL 本身能查出数据(把 XML 里的 SQL 复制到 Navicat 跑一遍),再检查三处:是否开了 mapUnderscoreToCamelCase、列名和 property 是否一致、是否该用 resultMap 手动映射。
foreach 批量插入报 packet 报错怎么办?
SQL 过长触发数据库包大小限制,把 List 按 200~500 条一批拆分后再插入,或者改用 JDBC 的 rewriteBatchedStatements=true 参数。
MyBatis 和 MyBatis-Plus 怎么选?
纯手写 SQL 用 MyBatis;CRUD 为主又想少写 XML,用 MyBatis-Plus,它在 MyBatis 核心之上提供了通用 Mapper 和条件构造器,两者可以共存,已有 MyBatis 项目接入成本很低。