MyBatis-Plus is an enhanced toolkit for MyBatis providing CRUD operations, query wrappers, pagination, code generation, and Spring Boot integration.
npx @tessl/cli install tessl/maven-com-baomidou--mybatis-plus@3.5.00
# MyBatis-Plus
1
2
MyBatis-Plus is a powerful enhancement toolkit for MyBatis that dramatically simplifies Java database development. It provides out-of-the-box features including automatic CRUD operations, flexible query wrappers with lambda-style API support, code generation, pagination, optimistic locking, and comprehensive Spring Boot integration while maintaining full backward compatibility with standard MyBatis.
3
4
## Package Information
5
6
- **Package Name**: mybatis-plus
7
- **Package Type**: Maven
8
- **Language**: Java
9
- **Installation**:
10
```xml
11
<dependency>
12
<groupId>com.baomidou</groupId>
13
<artifactId>mybatis-plus-boot-starter</artifactId>
14
<version>3.5.7</version>
15
</dependency>
16
```
17
18
## Core Imports
19
20
```java
21
// Core mapper and service imports
22
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
23
import com.baomidou.mybatisplus.extension.service.IService;
24
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
25
26
// Query wrapper imports
27
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
28
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
29
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
30
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
31
32
// Annotation imports
33
import com.baomidou.mybatisplus.annotation.TableName;
34
import com.baomidou.mybatisplus.annotation.TableId;
35
import com.baomidou.mybatisplus.annotation.TableField;
36
import com.baomidou.mybatisplus.annotation.IdType;
37
38
// Pagination imports
39
import com.baomidou.mybatisplus.core.metadata.IPage;
40
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
41
```
42
43
## Basic Usage
44
45
```java
46
// Entity definition with annotations
47
@TableName("user")
48
public class User {
49
@TableId(type = IdType.AUTO)
50
private Long id;
51
52
@TableField("user_name")
53
private String name;
54
55
private Integer age;
56
private String email;
57
58
// getters and setters...
59
}
60
61
// Mapper interface extending BaseMapper
62
public interface UserMapper extends BaseMapper<User> {
63
// Custom methods can be added here
64
}
65
66
// Service interface and implementation
67
public interface UserService extends IService<User> {
68
}
69
70
@Service
71
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
72
}
73
74
// Usage examples
75
@Autowired
76
private UserService userService;
77
78
// Basic CRUD operations
79
User user = new User();
80
user.setName("John");
81
user.setAge(25);
82
user.setEmail("john@example.com");
83
84
// Save user
85
userService.save(user);
86
87
// Query with wrapper
88
QueryWrapper<User> wrapper = new QueryWrapper<>();
89
wrapper.eq("age", 25).like("name", "John");
90
List<User> users = userService.list(wrapper);
91
92
// Lambda query
93
List<User> adults = userService.lambdaQuery()
94
.ge(User::getAge, 18)
95
.list();
96
97
// Pagination
98
Page<User> page = new Page<>(1, 10);
99
IPage<User> userPage = userService.page(page, wrapper);
100
```
101
102
## Architecture
103
104
MyBatis-Plus is organized into several key components:
105
106
- **Core Module**: BaseMapper interface, query wrappers, metadata handling, and configuration
107
- **Extension Module**: Service layer, plugins, Active Record support, and utility classes
108
- **Annotation Module**: Entity mapping annotations and enums
109
- **Generator Module**: Code generation capabilities with multiple template engines
110
- **Spring Boot Starters**: Auto-configuration and seamless Spring Boot integration
111
112
## Capabilities
113
114
### Core CRUD Operations
115
116
BaseMapper interface providing comprehensive database operations with automatic SQL generation for standard CRUD operations.
117
118
```java { .api }
119
public interface BaseMapper<T> {
120
int insert(T entity);
121
int deleteById(Serializable id);
122
int updateById(T entity);
123
T selectById(Serializable id);
124
List<T> selectList(Wrapper<T> queryWrapper);
125
Long selectCount(Wrapper<T> queryWrapper);
126
// ... additional methods
127
}
128
```
129
130
[Core CRUD Operations](./core-crud.md)
131
132
### Query Building
133
134
Flexible query wrapper system supporting both string-based and lambda-style conditions for building complex SQL queries.
135
136
```java { .api }
137
public class QueryWrapper<T> extends AbstractWrapper<T, String, QueryWrapper<T>> {
138
public QueryWrapper<T> eq(String column, Object val);
139
public QueryWrapper<T> ne(String column, Object val);
140
public QueryWrapper<T> gt(String column, Object val);
141
public QueryWrapper<T> like(String column, Object val);
142
// ... additional condition methods
143
}
144
145
public class LambdaQueryWrapper<T> extends AbstractLambdaWrapper<T, LambdaQueryWrapper<T>> {
146
public LambdaQueryWrapper<T> eq(SFunction<T, ?> fn, Object val);
147
public LambdaQueryWrapper<T> ne(SFunction<T, ?> fn, Object val);
148
public LambdaQueryWrapper<T> gt(SFunction<T, ?> fn, Object val);
149
// ... additional lambda condition methods
150
}
151
```
152
153
[Query Building](./query-building.md)
154
155
### Service Layer
156
157
High-level service interface providing business-logic-focused methods built on top of BaseMapper functionality.
158
159
```java { .api }
160
public interface IService<T> {
161
boolean save(T entity);
162
boolean saveBatch(Collection<T> entityList);
163
boolean saveOrUpdate(T entity);
164
boolean removeById(Serializable id);
165
boolean updateById(T entity);
166
T getById(Serializable id);
167
List<T> list();
168
List<T> list(Wrapper<T> queryWrapper);
169
<E extends IPage<T>> E page(E page, Wrapper<T> queryWrapper);
170
long count(Wrapper<T> queryWrapper);
171
// ... additional service methods
172
}
173
```
174
175
[Service Layer](./service-layer.md)
176
177
### Entity Annotations
178
179
Comprehensive annotation system for mapping Java entities to database tables with support for custom naming, field strategies, and special column handling.
180
181
```java { .api }
182
@Target(ElementType.TYPE)
183
public @interface TableName {
184
String value() default "";
185
String schema() default "";
186
boolean keepGlobalPrefix() default false;
187
String resultMap() default "";
188
boolean autoResultMap() default false;
189
}
190
191
@Target(ElementType.FIELD)
192
public @interface TableId {
193
String value() default "";
194
IdType type() default IdType.NONE;
195
}
196
197
@Target(ElementType.FIELD)
198
public @interface TableField {
199
String value() default "";
200
boolean exist() default true;
201
String condition() default "";
202
String update() default "";
203
FieldStrategy insertStrategy() default FieldStrategy.DEFAULT;
204
FieldStrategy updateStrategy() default FieldStrategy.DEFAULT;
205
FieldStrategy whereStrategy() default FieldStrategy.DEFAULT;
206
FieldFill fill() default FieldFill.DEFAULT;
207
boolean select() default true;
208
boolean keepGlobalFormat() default false;
209
JdbcType jdbcType() default JdbcType.UNDEFINED;
210
Class<? extends TypeHandler> typeHandler() default UnknownTypeHandler.class;
211
String numericScale() default "";
212
}
213
```
214
215
[Entity Annotations](./annotations.md)
216
217
### Code Generation
218
219
Automated code generation system for creating entity classes, mapper interfaces, service classes, and controller classes from database schemas.
220
221
```java { .api }
222
public class AutoGenerator {
223
public void execute();
224
public AutoGenerator setGlobalConfig(GlobalConfig globalConfig);
225
public AutoGenerator setDataSourceConfig(DataSourceConfig dataSourceConfig);
226
public AutoGenerator setPackageConfig(PackageConfig packageConfig);
227
public AutoGenerator setStrategyConfig(StrategyConfig strategyConfig);
228
public AutoGenerator setTemplateConfig(TemplateConfig templateConfig);
229
}
230
231
public class GlobalConfig {
232
public GlobalConfig setOutputDir(String outputDir);
233
public GlobalConfig setFileOverride(boolean fileOverride);
234
public GlobalConfig setAuthor(String author);
235
public GlobalConfig setEnableKotlin(boolean enableKotlin);
236
public GlobalConfig setSwagger(boolean swagger);
237
public GlobalConfig setDateType(DateType dateType);
238
}
239
```
240
241
[Code Generation](./code-generation.md)
242
243
### Pagination
244
245
Built-in pagination support with automatic count queries and flexible page configuration options.
246
247
```java { .api }
248
public interface IPage<T> extends Serializable {
249
List<T> getRecords();
250
IPage<T> setRecords(List<T> records);
251
long getTotal();
252
IPage<T> setTotal(long total);
253
long getSize();
254
IPage<T> setSize(long size);
255
long getCurrent();
256
IPage<T> setCurrent(long current);
257
default long getPages();
258
default boolean hasNext();
259
default boolean hasPrevious();
260
}
261
262
public class Page<T> implements IPage<T> {
263
public Page();
264
public Page(long current, long size);
265
public Page(long current, long size, long total);
266
public Page(long current, long size, boolean searchCount);
267
public Page(long current, long size, long total, boolean searchCount);
268
}
269
```
270
271
[Pagination](./pagination.md)
272
273
### Active Record Pattern
274
275
Active Record pattern support allowing entities to perform database operations directly without requiring separate mapper or service classes.
276
277
```java { .api }
278
public abstract class Model<T extends Model<?>> implements Serializable, Cloneable {
279
public boolean insert();
280
public boolean insertOrUpdate();
281
public boolean updateById();
282
public boolean update(Wrapper<T> updateWrapper);
283
public boolean deleteById();
284
public boolean delete(Wrapper<T> queryWrapper);
285
public T selectById();
286
public T selectOne(Wrapper<T> queryWrapper);
287
public List<T> selectList(Wrapper<T> queryWrapper);
288
public <E extends IPage<T>> E selectPage(E page, Wrapper<T> queryWrapper);
289
public long selectCount(Wrapper<T> queryWrapper);
290
}
291
```
292
293
[Active Record Pattern](./active-record.md)
294
295
### Plugins and Interceptors
296
297
Extensible plugin system for adding cross-cutting functionality like pagination, optimistic locking, tenant isolation, and SQL security.
298
299
```java { .api }
300
public class MybatisPlusInterceptor implements Interceptor {
301
public void addInnerInterceptor(InnerInterceptor innerInterceptor);
302
public List<InnerInterceptor> getInterceptors();
303
public void setProperties(Properties properties);
304
}
305
306
public interface InnerInterceptor {
307
default boolean willDoQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException;
308
default void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException;
309
default boolean willDoUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException;
310
default void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException;
311
}
312
313
public class PaginationInnerInterceptor implements InnerInterceptor {
314
public PaginationInnerInterceptor();
315
public PaginationInnerInterceptor(DbType dbType);
316
public void setMaxLimit(Long maxLimit);
317
public void setOverflow(boolean overflow);
318
}
319
```
320
321
[Plugins and Interceptors](./plugins.md)
322
323
### Spring Boot Integration
324
325
Seamless Spring Boot integration with auto-configuration, properties binding, and starter dependencies.
326
327
```java { .api }
328
@ConfigurationProperties(prefix = "mybatis-plus")
329
public class MybatisPlusProperties {
330
private String[] mapperLocations;
331
private String typeAliasesPackage;
332
private Class<?> typeAliasesSuperType;
333
private String typeHandlersPackage;
334
private ExecutorType executorType;
335
private Properties configurationProperties;
336
private GlobalConfig globalConfig;
337
// ... getters and setters
338
}
339
340
@Configuration
341
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
342
@ConditionalOnSingleCandidate(DataSource.class)
343
@EnableConfigurationProperties(MybatisPlusProperties.class)
344
@AutoConfigureAfter({DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class})
345
public class MybatisPlusAutoConfiguration implements InitializingBean {
346
@Bean
347
@ConditionalOnMissingBean
348
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception;
349
350
@Bean
351
@ConditionalOnMissingBean
352
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory);
353
}
354
```
355
356
[Spring Boot Integration](./spring-boot.md)
357
358
### Utility Classes
359
360
Essential utility classes providing helper methods for common database operations, SQL execution, and metadata handling.
361
362
```java { .api }
363
// SQL execution utilities
364
public class SqlHelper {
365
public static boolean retBool(Integer result);
366
public static boolean executeBatch(Class<?> entityClass, Log log, Collection<T> list, int batchSize, BiConsumer<SqlSession, T> consumer);
367
public static int executeBatch(Class<?> entityClass, Log log, Collection<T> list, int batchSize, BiPredicate<SqlSession, T> predicate);
368
}
369
370
// Raw SQL execution
371
public class SqlRunner {
372
public SqlRunner(DataSource dataSource);
373
public Map<String, Object> selectOne(String sql, Object... args);
374
public List<Map<String, Object>> selectList(String sql, Object... args);
375
public int insert(String sql, Object... args);
376
public int update(String sql, Object... args);
377
public int delete(String sql, Object... args);
378
}
379
380
// JDBC utilities
381
public class JdbcUtils {
382
public static DbType getDbType(String jdbcUrl);
383
public static String getJdbcUrl(DataSource dataSource);
384
public static DataSource getDataSource(String dataSourceName);
385
}
386
387
// Simplified querying utilities
388
public class SimpleQuery {
389
public static <T> List<T> list(LambdaQueryWrapper<T> wrapper);
390
public static <T> T one(LambdaQueryWrapper<T> wrapper);
391
public static <T> Map<String, Object> map(LambdaQueryWrapper<T> wrapper);
392
public static <T> Object obj(LambdaQueryWrapper<T> wrapper);
393
public static <T> Long count(LambdaQueryWrapper<T> wrapper);
394
}
395
396
// Table metadata utilities
397
public class TableInfoHelper {
398
public static TableInfo getTableInfo(Class<?> clazz);
399
public static void initTableInfo(MapperBuilderAssistant builderAssistant, Class<?> clazz);
400
public static String getTableName(Class<?> clazz);
401
public static List<TableFieldInfo> getFieldList(Class<?> clazz);
402
}
403
```
404
405
## Types
406
407
```java { .api }
408
// Function interface for lambda expressions
409
@FunctionalInterface
410
public interface SFunction<T, R> extends Function<T, R>, Serializable {
411
}
412
413
// Wrapper base class
414
public abstract class Wrapper<T> implements ISqlSegment, Serializable {
415
public abstract T getEntity();
416
public abstract String getSqlSegment();
417
public abstract List<Map<String, Object>> getParamNameValuePairs();
418
public abstract String getCustomSqlSegment();
419
public abstract String getExpression();
420
public abstract boolean isEmptyOfWhere();
421
public abstract boolean isEmptyOfNormal();
422
public abstract boolean nonEmpty();
423
public abstract void clear();
424
}
425
426
// Primary key generation strategies
427
public enum IdType {
428
AUTO(0), // Database auto-increment
429
NONE(1), // No primary key
430
INPUT(2), // User input
431
ASSIGN_ID(3), // Assign ID (snowflake)
432
ASSIGN_UUID(4); // Assign UUID
433
}
434
435
// Field fill strategies
436
public enum FieldFill {
437
DEFAULT, // Default, no auto-fill
438
INSERT, // Fill on insert
439
UPDATE, // Fill on update
440
INSERT_UPDATE; // Fill on insert and update
441
}
442
443
// Field strategy for conditions
444
public enum FieldStrategy {
445
IGNORED, // Ignore null and empty values
446
NOT_NULL, // Ignore null values only
447
NOT_EMPTY, // Ignore null and empty values
448
DEFAULT, // Use global default strategy
449
NEVER; // Never ignore
450
}
451
452
// Database types
453
public enum DbType {
454
MYSQL, MARIADB, ORACLE, DB2, H2, HSQL, SQLITE,
455
POSTGRE_SQL, SQL_SERVER2005, SQL_SERVER, DM,
456
XU_GU, KINGBASE_ES, PHOENIX, GAUSS, CLICK_HOUSE,
457
GBASE, GBASE_8S, OSCAR, SYBASE, OCEAN_BASE,
458
FIREBIRD, HIGH_GO, CUBRID, GOLDILOCKS, CSIIDB,
459
SAP_HANA, IMPALA, VERTICA, XCloud, REDSHIFT,
460
OPENGAUSS, TDENGINE, INFORMIX, SINODB, UXDB,
461
LEALONE, ALIYUN_ADS, PRESTO, TRINO, STARROCKS,
462
CLICKSTAR, POLARDBX;
463
}