Comprehensive Beginner’s Guide to MyBatis-Plus with Spring Boot
This article introduces MyBatis-Plus, outlines its non‑intrusive features and CRUD enhancements, walks through integrating it with a Spring Boot project, demonstrates entity, mapper and service definitions, explains common annotations, showcases the powerful Wrapper condition builder, and covers pagination configuration for everyday backend development.
Overview
MyBatis-Plus (MP) is an enhancement tool for MyBatis that adds powerful CRUD capabilities without altering existing code. Its key features include non‑intrusive integration, minimal performance impact, built‑in generic Mapper and Service, Lambda query support, multiple primary‑key strategies, ActiveRecord mode, global method injection, code generator, pagination plugin for many databases, performance analysis, and global interceptors for safe delete/update.
Quick Start
Create a Spring Boot project and add the following Maven dependencies:
<!-- MySQL driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<!-- MyBatis‑Plus starter -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>Add the datasource configuration to application.yml (or application.properties) and start the application to verify it runs.
Usage Example
Create a table tb_user in MySQL:
CREATE TABLE `tb_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`user_no` varchar(255) NOT NULL COMMENT '编号',
`nickname` varchar(255) DEFAULT NULL COMMENT '昵称',
`email` varchar(255) DEFAULT NULL COMMENT '邮箱',
`phone` varchar(255) NOT NULL COMMENT '手机号',
`gender` tinyint(4) NOT NULL DEFAULT '0' COMMENT '性别 0:男生 1:女生',
`birthday` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '出生日期',
`is_delete` tinyint(4) NOT NULL DEFAULT '0' COMMENT '删除标志 0:否 1:是',
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;Define the entity class:
@Data
@TableName("tb_user")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String userNo;
private String nickname;
private String email;
private String phone;
private Integer gender;
private Date birthday;
private Integer isDelete;
private Date createTime;
private Date updateTime;
}Create a mapper interface extending BaseMapper<User>:
public interface UserDAO extends BaseMapper<User> { }Configure component scanning in the main class:
@SpringBootApplication
@MapperScan(basePackages = "com.shepherd.mybatisplus.demo.dao")
public class MybatisPlusDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusDemoApplication.class, args);
}
}Write a test class to insert and list records:
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserServiceTest {
@Resource
private UserService userService;
@Resource
private UserDAO userDAO;
@Test
public void testAdd() {
User user = User.builder()
.id(1L)
.userNo("001")
.nickname("大哥")
.email("[email protected]")
.phone("1234556")
.birthday(new Date())
.build();
userDAO.insert(user);
}
@Test
public void testList() {
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
List<User> users = userDAO.selectList(queryWrapper);
System.out.println(users);
}
}The test output shows a single record retrieved, confirming that MP automatically maps table and column names and provides CRUD methods without extra SQL.
Common Annotations
@TableName : specifies the table name; optional if class name matches the table.
@TableId : defines primary‑key strategy (AUTO, NONE, INPUT, ASSIGN_ID, ASSIGN_UUID).
@TableField : customizes column mapping, field strategy, fill policy, select flag, type handler, etc.
For fields that use a custom typeHandler, enable autoResultMap=true on the entity’s @TableName to make the handler effective.
CRUD Interfaces
MyBatis‑Plus provides two sets of CRUD interfaces:
Mapper CRUD : extend BaseMapper<Entity> to get methods such as insert, selectById, updateById, deleteById.
Service CRUD : define a service interface extending IService<Entity> and implement it by extending ServiceImpl<Mapper, Entity>. This adds higher‑level methods like getById, list, page, removeById.
Condition Wrapper
MP’s Wrapper (including QueryWrapper, LambdaQueryWrapper, UpdateWrapper, LambdaUpdateWrapper) builds WHERE clauses fluently. Common methods include: eq, ne, gt, ge, lt, le – comparison operators. like, notLike, likeLeft, likeRight – pattern matching. in, notIn, inSql, notInSql – set membership. between, notBetween – range queries. or, and, nested – logical grouping. orderByAsc, orderByDesc, groupBy, having – ordering and aggregation. func – conditional method chaining.
Example of a dynamic query:
public List<BrandDTO> getList(BrandQuery query) {
LambdaQueryWrapper<Brand> qw = new LambdaQueryWrapper<>();
if (query.getCategoryId() != null) {
qw.eq(Brand::getCategoryId, query.getCategoryId());
}
if (StringUtils.isNotBlank(query.getLetter())) {
qw.eq(Brand::getLetter, query.getLetter());
}
if (StringUtils.isNotBlank(query.getName())) {
qw.likeRight(Brand::getName, query.getName());
}
return brandDAO.selectList(qw).stream()
.map(this::toBrandDTO)
.collect(Collectors.toList());
}Pagination
Enable pagination by registering MybatisPlusInterceptor with a PaginationInnerInterceptor for the target DB type:
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}Conclusion
The tutorial covers the essential steps to get started with MyBatis‑Plus: overview of features, Maven setup, entity and mapper definitions, service layer, common annotations, CRUD interfaces, the expressive Wrapper API, and pagination configuration. These components together enable fast, type‑safe CRUD development in Spring Boot projects.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Shepherd Advanced Notes
Dedicated to sharing advanced Java technical insights, daily work snippets, and the power of persistent effort.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
