Maven Dependencies
For Spring Boot 2
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>LATEST_VERSION</version>
</dependency>
For Spring Boot 3
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>LATEST_VERSION</version>
</dependency>
For Standard Spring
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>LATEST_VERSION</version>
</dependency>
Note: Do not include the standard MyBatis or mybatis-spring-boot-starter dependencies alongside MyBatis-Plus to prevent version conflicts.
Mapper Interface Definition
Create an interface that extends BaseMapper<T> to inherit basic CRUD operations.
@Repository
public interface EmployeeMapper extends BaseMapper<Employee> {
// All standard CRUD operations are pre-implemented
}
Configuration Class for Mapper Scanning
Set up a configuration clas to define the mapper package location and enable transaction management.
@Configuration
@MapperScan("com.example.data.mapper")
@EnableTransactionManagement
public class MyBatisPlusConfiguration {
}
SQL Execution Loggging
Enable logging of executed SQL statements to the console for debugging.
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
Database Configuration Example
Example configuration for connecting to a MySQL 5.7 database.
spring.datasource.username=dbuser
spring.datasource.password=securepass
spring.datasource.url=jdbc:mysql://localhost:3306/app_db?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
For MySQL 8, use driver com.mysql.cj.jdbc.Driver and ensure the serverTimezone parameter is set in the URL.
Primary Key Generation Strategies
Define the primary key generation strategy in your entity class.
public class Employee {
@TableId(type = IdType.AUTO)
private Long employeeId;
private String fullName;
private Integer years;
private String contactEmail;
}
Common IdType strategies include:
AUTO: Database auto-increment.ASSIGN_ID: Distributed unique ID using the Snowflake algorithm (default).UUID: Universally unique identifier. The Snowflake algorithm combines a timestamp, machine identifier, and sequence number to generate IDs that are highly scalable and globally unique.
Automatic Field Population
Automatically set fields like creation and modification timestamps.
Entity Class Annotation
public class Employee {
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createdAt;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updatedAt;
}
Meta Object Handler Implementation
@Component
public class AuditFieldHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.strictInsertFill(metaObject, "createdAt", LocalDateTime.class, LocalDateTime.now());
this.strictInsertFill(metaObject, "updatedAt", LocalDateTime.class, LocalDateTime.now());
}
@Override
public void updateFill(MetaObject metaObject) {
this.strictUpdateFill(metaObject, "updatedAt", LocalDateTime.class, LocalDateTime.now());
}
}
Optimistic Locking Implementation
Prevent data conflicts during concurrent updates using a version field.
Add Version Field to Entity
public class Employee {
@Version
private Integer revision;
}
Register the Interceptor
@Configuration
public class MyBatisPlusConfiguration {
@Bean
public MybatisPlusInterceptor dataInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
The update operation will then include a check: SET ... WHERE revision = old_revision.
Logical Deletion
Mark records as deleted instead of physically removing them.
Entity Configuration
public class Employee {
@TableLogic
private Integer isDeleted;
}
Application Configuration
mybatis-plus:
global-config:
db-config:
logic-delete-field: isDeleted
logic-delete-value: 1
logic-not-delete-value: 0
Subsequent select operations automatically filter out records where isDeleted = 1.
Conditional Query Wrapper
Construct dynamic SQL queries using QueryWrapper.
@Test
void queryWithWrapper() {
QueryWrapper<Employee> query = new QueryWrapper<>();
query.isNotNull("fullName")
.ge("years", 25)
.like("contactEmail", "@company.com");
List<Employee> list = employeeMapper.selectList(query);
list.forEach(System.out::println);
}
@Test
void queryBetween() {
QueryWrapper<Employee> query = new QueryWrapper<>();
query.between("years", 20, 30);
Long count = employeeMapper.selectCount(query);
System.out.println(count);
}
@Test
void queryOrdered() {
QueryWrapper<Employee> query = new QueryWrapper<>();
query.orderByDesc("employeeId");
List<Employee> list = employeeMapper.selectList(query);
list.forEach(System.out::println);
}
Code Generator Setup
Automatically generate entity, mapper, service, and controller classes from database tables.
Required Dependenceis
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>LATEST_VERSION</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>LATEST_VERSION</version>
</dependency>
Generator Configuration Script
public class CodeGenerator {
public static void main(String[] args) {
AutoGenerator generator = new AutoGenerator();
// Global Configuration
GlobalConfig globalConfig = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
globalConfig.setOutputDir(projectPath + "/src/main/java");
globalConfig.setAuthor("DevTeam");
globalConfig.setOpen(false);
globalConfig.setFileOverride(false);
globalConfig.setIdType(IdType.ASSIGN_ID);
globalConfig.setDateType(DateType.ONLY_DATE);
globalConfig.setSwagger2(true);
generator.setGlobalConfig(globalConfig);
// Data Source Configuration
DataSourceConfig dataSource = new DataSourceConfig();
dataSource.setUrl("jdbc:mysql://localhost:3306/app_db?useSSL=false");
dataSource.setDriverName("com.mysql.cj.jdbc.Driver");
dataSource.setUsername("dbuser");
dataSource.setPassword("securepass");
dataSource.setDbType(DbType.MYSQL);
generator.setDataSource(dataSource);
// Package Configuration
PackageConfig packageConfig = new PackageConfig();
packageConfig.setModuleName("system");
packageConfig.setParent("com.example.application");
packageConfig.setEntity("domain");
packageConfig.setMapper("repository");
packageConfig.setService("service");
packageConfig.setController("web");
generator.setPackageInfo(packageConfig);
// Generation Strategy
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("employee", "department"); // Tables to map
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setLogicDeleteFieldName("isDeleted");
// Auto-fill configuration
List<TableFill> fillList = new ArrayList<>();
fillList.add(new TableFill("created_at", FieldFill.INSERT));
fillList.add(new TableFill("updated_at", FieldFill.INSERT_UPDATE));
strategy.setTableFillList(fillList);
strategy.setVersionFieldName("revision"); // Optimistic lock field
generator.setStrategy(strategy);
generator.execute();
}
}