1. Introduction
MyBatis is a popular open-source persistence framework that provides alternatives to JDBC and Hibernate.
In this article, we’ll discuss an extension over MyBatis called MyBatis-Plus, loaded with many handy features offering rapid development and better efficiency.
2. MyBatis-Plus Setup
2.1. Maven Dependency
First, let’s add the following Maven dependency to our pom.xml.
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>3.5.7</version>
</dependency>
The latest version of the Maven dependency can be found here. Since this is the Spring Boot 3-based Maven dependency, we’ll also be required to add the spring-boot-starter dependency to our pom.xml.
Alternatively, we can add the following dependency when using Spring Boot 2:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.7</version>
</dependency>
Next, we’ll add the H2 dependency to our pom.xml for an in-memory database to verify the features and capabilities of MyBatis-Plus.
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.3.230</version>
</dependency>
Similarly, find the latest version of the Maven dependency here. We can also use MySQL for the integration.
2.2. Client
Once our setup is ready, let’s create the Client entity with a few properties like id, firstName, lastName, and email:
@TableName("client")
public class Client {
@TableId(type = IdType.AUTO)
private Long id;
private String firstName;
private String lastName;
private String email;
// getters and setters ...
}
Here, we’ve used MyBatis-Plus’s self-explanatory annotations like @TableName and @TableId for quick integration with the client table in the underlying database.
2.3. ClientMapper
Then, we’ll create the mapper interface for the Client entity – ClientMapper that extends the BaseMapper interface provided by MyBatis-Plus:
@Mapper
public interface ClientMapper extends BaseMapper<Client> {
}
The BaseMapper interface provides numerous default methods like insert(), selectOne(), updateById(), insertOrUpdate(), deleteById(), and deleteByIds() for CRUD operations.
2.4. ClientService
Next, let’s create the ClientService service interface extending the IService interface:
public interface ClientService extends IService<Client> {
}
The IService interface encapsulates the default implementations of CRUD operations and uses the BaseMapper interface to offer simple and maintainable basic database operations.
2.5. ClientServiceImpl
Last, we’ll create the ClientServiceImpl class:
@Service
public class ClientServiceImpl extends ServiceImpl<ClientMapper, Client> implements ClientService {
@Autowired
private ClientMapper clientMapper;
}
It’s the service implementation for the Client entity, injected with the ClientMapper dependency.
3. CRUD Operations
3.1. Create
Now that we’ve all the utility interfaces and classes ready, let’s use the ClientService interface to create the Client object:
Client client = new Client();
client.setFirstName("Anshul");
client.setLastName("Bansal");
client.setEmail("[email protected]");
clientService.save(client);
assertNotNull(client.getId());
We can observe the following logs when saving the client object once we set the logging level to DEBUG for the package com.baeldung.mybatisplus:
16:07:57.404 [main] DEBUG c.b.m.mapper.ClientMapper.insert - ==> Preparing: INSERT INTO client ( first_name, last_name, email ) VALUES ( ?, ?, ? )
16:07:57.414 [main] DEBUG c.b.m.mapper.ClientMapper.insert - ==> Parameters: Anshul(String), Bansal(String), [email protected](String)
16:07:57.415 [main] DEBUG c.b.m.mapper.ClientMapper.insert - <== Updates: 1
The logs generated by the ClientMapper interface show the insert query with the parameters and final number of rows inserted in the database.
3.2. Read
Next, let’s check out a few handy read methods like getById() and list():
assertNotNull(clientService.getById(2));
assertEquals(6, clientService.list())
Similarly, we can observe the following SELECT statement in the logs:
16:07:57.423 [main] DEBUG c.b.m.mapper.ClientMapper.selectById - ==> Preparing: SELECT id,first_name,last_name,email,creation_date FROM client WHERE id=?
16:07:57.423 [main] DEBUG c.b.m.mapper.ClientMapper.selectById - ==> Parameters: 2(Long)
16:07:57.429 [main] DEBUG c.b.m.mapper.ClientMapper.selectById - <== Total: 1
16:07:57.437 [main] DEBUG c.b.m.mapper.ClientMapper.selectList - ==> Preparing: SELECT id,first_name,last_name,email FROM client
16:07:57.438 [main] DEBUG c.b.m.mapper.ClientMapper.selectList - ==> Parameters:
16:07:57.439 [main] DEBUG c.b.m.mapper.ClientMapper.selectList - <== Total: 6
Also, the MyBatis-Plus framework comes with a few handy wrapper classes like QueryWrapper, LambdaQueryWrapper, and QueryChainWrapper:
Map<String, Object> map = Map.of("id", 2, "first_name", "Laxman");
QueryWrapper<Client> clientQueryWrapper = new QueryWrapper<>();
clientQueryWrapper.allEq(map);
assertNotNull(clientService.getBaseMapper().selectOne(clientQueryWrapper));
LambdaQueryWrapper<Client> lambdaQueryWrapper = new LambdaQueryWrapper<>();
lambdaQueryWrapper.eq(Client::getId, 3);
assertNotNull(clientService.getBaseMapper().selectOne(lambdaQueryWrapper));
QueryChainWrapper<Client> queryChainWrapper = clientService.query();
queryChainWrapper.allEq(map);
assertNotNull(clientService.getBaseMapper().selectOne(queryChainWrapper.getWrapper()));
Here, we’ve used the getBaseMapper() method of the ClientService interface to utilize the wrapper classes to let us write complex queries intuitively.
3.3. Update
Then, let’s take a look at a few ways to execute the updates:
Client client = clientService.getById(2);
client.setEmail("[email protected]");
clientService.updateById(client);
assertEquals("[email protected]", clientService.getById(2).getEmail());
Follow the console to check out the following logs:
16:07:57.440 [main] DEBUG c.b.m.mapper.ClientMapper.updateById - ==> Preparing: UPDATE client SET email=? WHERE id=?
16:07:57.441 [main] DEBUG c.b.m.mapper.ClientMapper.updateById - ==> Parameters: [email protected](String), 2(Long)
16:07:57.441 [main] DEBUG c.b.m.mapper.ClientMapper.updateById - <== Updates: 1
Similarly, we can use the LambdaUpdateWrapper class to update the Client objects:
LambdaUpdateWrapper<Client> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
lambdaUpdateWrapper.set(Client::getEmail, "[email protected]");
assertTrue(clientService.update(lambdaUpdateWrapper));
QueryWrapper<Client> clientQueryWrapper = new QueryWrapper<>();
clientQueryWrapper.allEq(Map.of("email", "[email protected]"));
assertThat(clientService.list(clientQueryWrapper).size()).isGreaterThan(5);
Once the client objects are updated, we use the QueryWrapper class to confirm the operation.
3.4. Delete
Similarly, we can use the removeById() or removeByMap() methods to delete the records:
clientService.removeById(1);
assertNull(clientService.getById(1));
Map<String, Object> columnMap = new HashMap<>();
columnMap.put("email", "[email protected]");
clientService.removeByMap(columnMap);
assertEquals(0, clientService.list().size());
The logs for the delete operation would look like this:
21:55:12.938 [main] DEBUG c.b.m.mapper.ClientMapper.deleteById - ==> Preparing: DELETE FROM client WHERE id=?
21:55:12.938 [main] DEBUG c.b.m.mapper.ClientMapper.deleteById - ==> Parameters: 1(Long)
21:55:12.938 [main] DEBUG c.b.m.mapper.ClientMapper.deleteById - <== Updates: 1
21:57:14.278 [main] DEBUG c.b.m.mapper.ClientMapper.delete - ==> Preparing: DELETE FROM client WHERE (email = ?)
21:57:14.286 [main] DEBUG c.b.m.mapper.ClientMapper.delete - ==> Parameters: [email protected](String)
21:57:14.287 [main] DEBUG c.b.m.mapper.ClientMapper.delete - <== Updates: 5
Similar to the update logs, these logs show the delete query with the parameters and total rows deleted from the database.
4. Extra Features
Let’s discuss a few handy features available in MyBatis-Plus as extensions over MyBatis.
4.1. Batch Operations
First and foremost is the ability to perform common CRUD operations in batches thereby improving performance and efficiency:
Client client2 = new Client();
client2.setFirstName("Harry");
Client client3 = new Client();
client3.setFirstName("Ron");
Client client4 = new Client();
client4.setFirstName("Hermione");
// create in batches
clientService.saveBatch(Arrays.asList(client2, client3, client4));
assertNotNull(client2.getId());
assertNotNull(client3.getId());
assertNotNull(client4.getId());
Likewise, let’s check out the logs to see the batch inserts in action:
16:07:57.419 [main] DEBUG c.b.m.mapper.ClientMapper.insert - ==> Preparing: INSERT INTO client ( first_name ) VALUES ( ? )
16:07:57.419 [main] DEBUG c.b.m.mapper.ClientMapper.insert - ==> Parameters: Harry(String)
16:07:57.421 [main] DEBUG c.b.m.mapper.ClientMapper.insert - ==> Parameters: Ron(String)
16:07:57.421 [main] DEBUG c.b.m.mapper.ClientMapper.insert - ==> Parameters: Hermione(String)
Also, we’ve got methods like updateBatchById(), saveOrUpdateBatch(), and removeBatchByIds() to perform save, update, or delete operations for a collection of objects in batches.
4.2. Pagination
MyBatis-Plus framework offers an intuitive way to paginate the query results.
All we need is to declare the MyBatisPlusInterceptor class as a Spring Bean and add the PaginationInnerInterceptor class defined with database type as an inner interceptor:
@Configuration
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
}
}
Then, we can use the Page class to paginate the records. For instance, let’s fetch the second page with three results:
Page<Client> page = Page.of(2, 3);
clientService.page(page, null).getRecords();
assertEquals(3, clientService.page(page, null).getRecords().size());
So, we can observe the following logs for the above operation:
16:07:57.487 [main] DEBUG c.b.m.mapper.ClientMapper.selectList - ==> Preparing: SELECT id,first_name,last_name,email FROM client LIMIT ? OFFSET ?
16:07:57.487 [main] DEBUG c.b.m.mapper.ClientMapper.selectList - ==> Parameters: 3(Long), 3(Long)
16:07:57.488 [main] DEBUG c.b.m.mapper.ClientMapper.selectList - <== Total: 3
Likewise, these logs show the select query with the parameters and total rows selected from the database.
4.3. Streaming Query
MyBatis-Plus offers support for streaming queries through methods like selectList(), selectByMap(), and selectBatchIds(), letting us process big data and meet the performance objectives.
For instance, let’s check out the selectList() method available through the ClientService interface:
clientService.getBaseMapper()
.selectList(Wrappers.emptyWrapper(), resultContext ->
assertNotNull(resultContext.getResultObject()));
Here, we’ve used the getResultObject() method to get every record from the database.
Likewise, we’ve got the getResultCount() method that returns the count of results being processed and the stop() method to halt the processing of the result set.
4.4. Auto-fill
Being a fairly opinionated and intelligent framework, MyBatis-Plus also supports automatically filling fields for insert and update operations.
For example, we can use the @TableField annotation to set the creationDate when inserting a new record and lastModifiedDate in the event of an update:
public class Client {
// ...
@TableField(fill = FieldFill.INSERT)
private LocalDateTime creationDate;
@TableField(fill = FieldFill.UPDATE)
private LocalDateTime lastModifiedDate;
// getters and setters ...
}
Now, MyBatis-Plus will fill the creation_date and last_modified_date columns automatically with every insert and update query.
4.5. Logical Delete
MyBatis-Plus framework offers a simple and efficient strategy to let us logically delete the record by flagging it in the database.
We can enable the feature by using the @TableLogic annotation over the deleted property:
@TableName("client")
public class Client {
// ...
@TableLogic
private Integer deleted;
// getters and setters ...
}
Now, the framework will automatically handle the logical deletion of the records when performing database operations.
So, let’s remove the Client object and try to read the same:
clientService.removeById(harry);
assertNull(clientService.getById(harry.getId()));
Observe the following logs to check out the update query setting the value of the deleted property to 1 and using the 0 value while running the select query on the database:
15:38:41.955 [main] DEBUG c.b.m.mapper.ClientMapper.deleteById - ==> Preparing: UPDATE client SET last_modified_date=?, deleted=1 WHERE id=? AND deleted=0
15:38:41.955 [main] DEBUG c.b.m.mapper.ClientMapper.deleteById - ==> Parameters: null, 7(Long)
15:38:41.957 [main] DEBUG c.b.m.mapper.ClientMapper.deleteById - <== Updates: 1
15:38:41.957 [main] DEBUG c.b.m.mapper.ClientMapper.selectById - ==> Preparing: SELECT id,first_name,last_name,email,creation_date,last_modified_date,deleted FROM client WHERE id=? AND deleted=0
15:38:41.957 [main] DEBUG c.b.m.mapper.ClientMapper.selectById - ==> Parameters: 7(Long)
15:38:41.958 [main] DEBUG c.b.m.mapper.ClientMapper.selectById - <== Total: 0
Also, it’s possible to modify the default configuration through the application.yml:
mybatis-plus:
global-config:
db-config:
logic-delete-field: deleted
logic-delete-value: 1
logic-not-delete-value: 0
The above configuration lets us to change the name of the delete field with delete and active values.
4.6. Code Generator
MyBatis-Plus offers an automatic code generation feature to avoid manually creating redundant code like entity, mapper, and service interfaces.
First, let’s add the latest mybatis-plus-generator dependency to our pom.xml:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.7</version>
</dependency>
Also, we’ll require the support of a template engine like Velocity or Freemarker.
Then, we can use MyBatis-Plus’s FastAutoGenerator class with the FreemarkerTemplateEngine class set as a template engine to connect the underlying database, scan all the existing tables, and generate the utility code:
FastAutoGenerator.create("jdbc:h2:file:~/mybatisplus", "sa", "")
.globalConfig(builder -> {
builder.author("anshulbansal")
.outputDir("../tutorials/mybatis-plus/src/main/java/")
.disableOpenDir();
})
.packageConfig(builder -> builder.parent("com.baeldung.mybatisplus").service("ClientService"))
.templateEngine(new FreemarkerTemplateEngine())
.execute();
Therefore, when the above program runs, it’ll generate the output files in the com.baeldung.mybatisplus package:
List<String> codeFiles = Arrays.asList("src/main/java/com/baeldung/mybatisplus/entity/Client.java",
"src/main/java/com/baeldung/mybatisplus/mapper/ClientMapper.java",
"src/main/java/com/baeldung/mybatisplus/service/ClientService.java",
"src/main/java/com/baeldung/mybatisplus/service/impl/ClientServiceImpl.java");
for (String filePath : codeFiles) {
Path path = Paths.get(filePath);
assertTrue(Files.exists(path));
}
Here, we’ve asserted that the automatically generated classes/interfaces like Client, ClientMapper, ClientService, and ClientServiceImpl exist at the corresponding paths.
4.7. Custom ID Generator
MyBatis-Plus framework allows implementing a custom ID generator using the IdentifierGenerator interface.
For instance, let’s create the TimestampIdGenerator class and implement the nextId() method of the IdentifierGenerator interface to return the System’s nanoseconds:
@Component
public class TimestampIdGenerator implements IdentifierGenerator {
@Override
public Long nextId(Object entity) {
return System.nanoTime();
}
}
Now, we can create the Client object setting the custom ID using the timestampIdGenerator bean:
Client client = new Client();
client.setId(timestampIdGenerator.nextId(client));
client.setFirstName("Harry");
clientService.save(client);
assertThat(timestampIdGenerator.nextId(harry)).describedAs(
"Since we've used the timestampIdGenerator, the nextId value is greater than the previous Id")
.isGreaterThan(harry.getId());
The logs will show the custom ID value generated by the TimestampIdGenerator class:
16:54:36.485 [main] DEBUG c.b.m.mapper.ClientMapper.insert - ==> Preparing: INSERT INTO client ( id, first_name, creation_date ) VALUES ( ?, ?, ? )
16:54:36.485 [main] DEBUG c.b.m.mapper.ClientMapper.insert - ==> Parameters: 678220507350000(Long), Harry(String), null
16:54:36.485 [main] DEBUG c.b.m.mapper.ClientMapper.insert - <== Updates: 1
The long value of id shown in the parameters is the system time in nanoseconds.
4.8. DB Migration
MyBatis-Plus offers an automatic mechanism to handle DDL migrations.
We require to simply extend the SimpleDdl class and override the getSqlFiles() method to return a list of paths of SQL files containing the database migration statements:
@Component
public class DBMigration extends SimpleDdl {
@Override
public List<String> getSqlFiles() {
return Arrays.asList("db/db_v1.sql", "db/db_v2.sql");
}
}
The underlying IdDL interface creates the ddl_history table to keep the history of DDL statements performed on the schema:
CREATE TABLE IF NOT EXISTS `ddl_history` (`script` varchar(500) NOT NULL COMMENT '脚本',`type` varchar(30) NOT NULL COMMENT '类型',`version` varchar(30) NOT NULL COMMENT '版本',PRIMARY KEY (`script`)) COMMENT = 'DDL 版本'
alter table client add column address varchar(255)
alter table client add column deleted int default 0
Note: this feature works with most databases like MySQL and PostgreSQL, but not H2.
5. Conclusion
In this introductory article, we’ve explored MyBatis-Plus – an extension over the popular MyBatis framework, loaded with many developer-friendly opinionated ways to perform CRUD operations on the database.
Also, we’ve seen a few handy features like batch operations, pagination, ID generation, and DB migration.
The complete code for this article is available over on GitHub.