使用过 MyBatis 的开发者大多都有类似感受:做单表 CRUD 时,往往需要为每张表单独编写一个 XML 映射文件。虽然借助代码生成器可以一次性生成实体类和映射配置,但只要后续数据库表结构发生调整,再次生成和维护就会变得非常繁琐,实际开发中并不高效,整体体验也不算理想。
最近在项目实践中发现,tkmybatis 能很好地解决这一类 MyBatis 单表开发痛点。它将常见的单表增删改查封装为通用 Mapper 接口,能够显著减少重复 XML 配置和样板代码。下面通过实战示例,详细看看如何在 Spring Boot 项目中整合 tkmybatis。
框架配置
首先需要引入以下依赖:
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
mysql
mysql-connector-ja va
runtime
com.alibaba
druid-spring-boot-starter
1.1.10
tk.mybatis
mapper-spring-boot-starter
2.1.2
org.projectlombok
lombok
1.16.10
true
com.alibaba
fastjson
1.2.31
org.springframework.boot
spring-boot-starter-web
2.1.4.RELEASE
接着配置数据源:
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
下面是示例中对应的建表 SQL 语句:
DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `user_phone` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE, INDEX `user_name_index`(`user_name`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES (1, 'evan', '26'); INSERT INTO `user` VALUES (2, 'evan11', '26');
类配置方法
实体类方法
这里通过 Lombok 简化实体类编写,省去了大量 getter/setter 代码。如果你对 IDEA 中因 Lombok 导致的报红提示比较在意,可以额外安装 Lombok 插件;即使不安装,也不会影响项目正常运行。
@Data
@Table(name="user")
public class UserModel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY,generator = "JDBC")
private Integer id;
@Column
private String userName;
@Column
private String userPhone;
}
几个常用注解的含义如下:@Table 用于指定数据库表名,@Column 用于映射表字段,@Id 用于标记主键字段(注意一个实体只能有一个主键)。另外,@Transient 用来标识临时或冗余属性,该字段不会与数据库中的任何列进行映射。
注意多数据源的情况
如果项目中使用了多数据源,那么 @Table 可以写成“数据库名.架构名.表名”的完整形式,例如:@Table(name="db.dbo.tableName"),以便更准确地指定目标表。

Service类
核心思路就是继承基础 Mapper 接口。tk.mybatis 提供的 BaseMapper 已经内置了常用的单表操作方法,能够覆盖绝大多数基础 CRUD 场景:
/** * 保存一个实体,null属性也会保存 * * @param record * @return */ int insert(T record); /** * 保存一个实体,null属性不会保存 * * @param record * @return */ int insertSelective(T record); /** * 根据实体属性作为条件进行删除,查询条件使用等号 */ int delete(T record); /** * 根据主键更新属性不为null的值 */ int updateByPrimaryKeySelective(T record); /** * 根据实体中的属性值进行查询,查询条件使用等号 */ Listselect(T record); /** * 查询全部结果,select(null)方法能达到同样的效果 */ List selectAll(); /** * 根据实体中的属性进行查询,只能有一个返回值,有多个结果是抛出异常,查询条件使用等号 */ T selectOne(T record); /** * 根据实体中的属性查询总数,查询条件使用等号 */ int selectCount(T record);
其中,MySqlMapper 还提供了批量插入能力,适合在 MySQL 等支持批量写入的数据库中使用:
/** * 批量插入,支持批量插入的数据库可以使用,例如MySQL,H2等,另外该接口限制实体包含`id`属性并且必须为自增列 */ public int insertList(ListrecordList); /** * 插入数据,限制为实体包含`id`属性并且必须为自增列,实体配置的主键策略无效 */ public int insertUseGeneratedKeys(T record);
IdsMapper 支持按照多个主键值进行批量查询或删除,多个 ID 使用逗号分隔:
/** * 根据主键@Id进行查询,多个Id以逗号,分割 * @param id * @return */ ListselectByIds(String ids); /** * 根据主键@Id进行删除,多个Id以逗号,分割 * @param id * @return */ int deleteByIds(String ids);
ConditionMapper 则适用于更灵活的动态条件查询与更新操作:
/** * 根据Condition条件进行查询 */ public ListselectByCondition(Object condition); /** * 根据Condition条件进行查询 */ public int selectCountByCondition(Object condition); /** * 根据Condition条件删除数据,返回删除的条数 */ public int deleteByCondition(Object condition); /** * 根据Condition条件更新实体`record`包含的全部属性,null值会被更新,返回更新的条数 */ public int updateByCondition(T record, Object condition); /** * 根据Condition条件更新实体`record`包含的全部属性,null值会被更新,返回更新的条数 */ public int updateByConditionSelective(T record, Object condition);
而 ExampleMapper 则延续了 MyBatis 中非常经典的 Example 条件构造方式:
/** * 根据Example条件进行查询 */ public ListselectByExample(Object example); /** * 根据Example条件进行查询,若有多条数据则抛出异常 */ public T selectOneByExample(Object example); /** * 根据Example条件进行查询总数 */ public int selectCountByExample(Object example); /** * 根据Example条件删除数据,返回删除的条数 */ public int deleteByExample(Object example); /** * 根据Example条件更新实体`record`包含的全部属性,null值会被更新,返回更新的条数 */ public int updateByExample(T record, Object example); /** * 根据Example条件更新实体`record`包含的不是null的属性值,返回更新的条数 */ public int updateByExampleSelective(T record, Object example);
使用方法
BaseMapper、IdsMapper、MySqlMapper 中的大多数方法,都会以实体类 T record 作为参数。执行查询时,框架会根据实体中非空属性自动拼接 where 条件,默认通过等号进行匹配。这种写法简单直接,非常适合快速完成常规单表查询。
ExampleMapper内方法使用说明
Example example = new Example(UserModel.class);
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo("id","1");
criteria.orEqualTo("userName","evan11");
Criteria 是 Example 的内部类,最终生成的 SQL 条件会统一包裹在一组括号中。它内置了丰富的条件拼装方法,比如 andEqualTo、orEqualTo、andGreaterThan、orGreaterThan 等,使用起来和 MyBatis 动态 SQL 思路比较接近,完整方法列表可以直接查看源码。

ExampleMapper内方法使用说明
这类方法都需要传入 tk.mybatis.mapper.entity.Example 对象。通常先进行实例化,再通过 createCriteria() 构造查询条件。
Example example = new Example(UserRole.class);//实例化 Example.Criteria criteria = example.createCriteria();
常见条件方法包括:
andEqualTo(String property,Object value) orEqualTo(String property,Object value) andGreaterThan(String property, Object value) orGreaterThan(String property, Object value)
下面给出一个简单的查询示例:
Example example = new Example(UserModel.class);
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo("id","1");
criteria.orEqualTo("userName","evan11");
List userModels = userDao.selectByExample(example);
最终生成的 SQL 如下所示:
Preparing: SELECT id,user_name,user_phone FROM user WHERE ( ( id = ? and user_name = ? ) ) Parameters: 1(String), evan11(String)
此外,andCondition(String condition) 支持直接传入自定义条件片段,例如 length(f_user_id)<5。而 likeTo() 方法默认不会自动补全百分号,因此在使用模糊查询时,需要自行拼接左 like、右 like 或全模糊匹配参数。其他扩展方法也不少,建议结合源码和实际业务场景灵活使用。
ConditionMapper内方法使用说明
Condition 本质上继承自 Example,在源码中提供了以下三个构造方法:
public Condition(Class> entityClass) {
super(entityClass);
}
public Condition(Class> entityClass, boolean exists) {
super(entityClass, exists);
}
public Condition(Class> entityClass, boolean exists, boolean notNull) {
super(entityClass, exists, notNull);
}
它的使用方式与 Example 基本一致,示例如下:
Condition condition = new Condition(UserRole.class);
Criteria criteria = condition.createCriteria();
criteria.andEqualTo("id","1");
criteria.orEqualTo("userName","evan11");
List userModels = userDao.selectByExample(example);
总结
总体来看,tkmybatis 的核心优势就在于:将 MyBatis 单表操作中大量重复的 XML 映射工作抽离出来,通过继承通用 Mapper 即可快速获得完整的 CRUD 能力。当数据库表结构发生变化时,通常只需要调整实体类即可,不必反复维护额外的 XML 文件。对于 Spring Boot + MyBatis 的中小型项目开发来说,这种方案不仅上手快,而且能够有效提升开发效率与维护性。希望这篇关于 Spring Boot 整合 tkmybatis 的实战配置与使用说明,能为你提供有价值的参考。
