Let's get started with a Microservice Architecture with Spring Cloud:
Guide to MyBatis-Flex
Last updated: March 18, 2026
1. Overview
MyBatis-Flex extends the MyBatis ecosystem by offering a more convenient programming model for common data access tasks.
In this tutorial, we’ll build a small Spring Boot 4 application to explore the core MyBatis-Flex workflow, from project setup to data access code. Specifically, we’ll define a simple entity and mapper, perform basic CRUD operations, create filtered queries with QueryWrapper, and paginate the results.
The examples in this article require Java 17 or later.
2. Set Up a Minimal Spring Boot Project
Spring Boot streamlines the MyBatis-Flex setup process, making it easier for us to focus on the mapper and query APIs.
2.1. Add the Dependencies
Although MyBatis-Flex removes much of the boilerplate usually associated with direct JDBC access, and we can use it as an alternative to JPA or Hibernate, it still depends on the Spring JDBC infrastructure for datasource configuration and management.
MyBatis-Flex supports more than forty different database types, including MySQL, PostgreSQL, Oracle, SQL Server, and SQLite. In this case, let’s use H2 as an in-memory database because it facilitates the creation of fast, isolated, and repeatable tests.
To that end, we add the MyBatis-Flex, Spring JDBC, H2, and Spring Boot Test Starter dependencies to a Spring Boot 4 pom.xml:
<dependency>
<groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-spring-boot4-starter</artifactId>
<version>1.11.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>4.0.3</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.4.240</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>4.0.3</version>
<scope>test</scope>
</dependency>
Before moving on, it’s worth checking the Maven Repository for newer versions.
2.2. Configure the DataSource (H2)
Next, let’s configure the datasource in src/main/resources/application.yml:
spring:
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:mem:mybatisflex
username: sa
password:
sql:
init:
mode: always
schema-locations: classpath:db/schema-h2.sql
data-locations: classpath:db/data-h2.sql
The jdbc:h2:mem:mybatisflex URL creates an in-memory database within the application context. The username sa with an empty password is the default for H2.
The spring.sql.init section instructs Spring Boot to initialize the datasource using SQL scripts. In this case, it loads the schema from src/main/resources/db/schema-h2.sql and the sample data from src/main/resources/db/data-h2.sql.
2.3. Enable Mapper Scanning
Finally, let’s enable mapper scanning in the main Spring Boot application class. In MyBatis-Flex, a mapper is the component that connects Java code to database operations on an entity:
@SpringBootApplication
@MapperScan("com.baeldung.mybatisflex.mapper")
public class MyBatisFlexApplication {
public static void main(String[] args) {
SpringApplication.run(MyBatisFlexApplication.class, args);
}
}
With mapper scanning enabled, Spring can detect AccountMapper, create a bean for it, and let us inject it into the tests.
3. Create an Entity and a Mapper
Now that the project is configured, let’s define the domain model and the mapper that MyBatis-Flex uses for persistence operations.
3.1. Define a Simple Entity With Annotations
First, we can start with a simple Account entity mapped to the tb_account table. MyBatis-Flex uses annotations to associate the class with the table and to customize how individual fields map to database columns:
@Table("tb_account")
public class Account {
@Id(keyType = KeyType.Auto)
private Long id;
@Column("user_name")
private String userName;
private Integer age;
private String status;
@Column("created_at")
private LocalDateTime createdAt;
// getters and setters
}
Here, @Table binds the class to the tb_account table, while @Id marks the primary key and configures it as an auto-generated value. Notably, we also use @Column where the Java field name doesn’t match the column name directly, such as userName and createdAt. The remaining fields follow the default naming convention, so no extra annotation is needed.
3.2. Create a Mapper Interface Extending BaseMapper<T>
Next, let’s define the mapper interface for Account. In MyBatis-Flex, the mapper is the component that exposes the data access operations for an entity:
@Mapper
public interface AccountMapper extends BaseMapper<Account> {
}
By extending BaseMapper<Account>, AccountMapper inherits a rich set of built-in operations for inserts, updates, deletes, and queries. This keeps the interface minimal while still providing everything we need for the examples in this article.
3.3. Initialize the Schema and Test Data
Before writing any Java code against the database, let’s add a small schema and a few sample rows. For that, we place both scripts under src/main/resources/db so that Spring Boot can load them automatically at startup.
First, we create schema-h2.sql:
CREATE TABLE IF NOT EXISTS tb_account (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
user_name VARCHAR(100) NOT NULL,
age INT,
status VARCHAR(20),
created_at TIMESTAMP
);
Next, let’s do data-h2.sql:
INSERT INTO tb_account (user_name, age, status, created_at)
VALUES ('sarah', 35, 'ACTIVE', TIMESTAMP '2024-01-15 10:00:00');
INSERT INTO tb_account (user_name, age, status, created_at)
VALUES ('mike', 17, 'INACTIVE', TIMESTAMP '2024-02-01 09:30:00');
INSERT INTO tb_account (user_name, age, status, created_at)
VALUES ('emma', 42, 'ACTIVE', TIMESTAMP '2024-03-10 14:15:00');
INSERT INTO tb_account (user_name, age, status, created_at)
VALUES ('tom', 20, 'ACTIVE', TIMESTAMP '2024-04-05 08:45:00');
The sample data gives us a predictable dataset for the integration tests. Since the rows differ in age, status, and creation time, we can reuse them across multiple examples without adding extra setup code in each test.
4. Basic CRUD Operations
Now that we have the basic model in place, let’s look at the data operations that we’re most likely to perform first in a real application:
- inserting
- reading
- updating
- removing
First, let’s inject the mapper directly into the test class:
@SpringBootTest
@Transactional
public class MyBatisFlexIntegrationTest {
@Autowired
private AccountMapper accountMapper;
// tests
}
At this point, we’re ready to start adding tests.
4.1. Insert and Retrieve by ID
Let’s try a simple persistence flow:
@Test
public void whenInsertAndSelectById_thenAccountIsPersisted() {
Account account = new Account();
account.setUserName("olivia");
account.setAge(28);
account.setStatus("ACTIVE");
account.setCreatedAt(LocalDateTime.of(2024, 5, 1, 12, 0));
accountMapper.insert(account);
Account persistedAccount = accountMapper.selectOneById(account.getId());
assertNotNull(account.getId());
assertNotNull(persistedAccount);
assertEquals("olivia", persistedAccount.getUserName());
}
Here, we created an Account, inserted it through the mapper, and then retrieved it by its generated id to verify that the record was stored correctly.
4.2. Update an Existing Record
Updating an existing record is just as easy.
First, let’s load an entity. Then, we modify one of its fields. Finally, let’s pass it back to the mapper to persist the change:
@Test
public void whenUpdatingAnAccount_thenTheNewStatusIsStored() {
Account account = accountMapper.selectOneById(1L);
account.setStatus("INACTIVE");
accountMapper.update(account);
Account updatedAccount = accountMapper.selectOneById(1L);
assertEquals("INACTIVE", updatedAccount.getStatus());
}
Reading the same row again confirms that the new value was written to the database as expected.
4.3. Delete Records
This test confirms that deleteById() removes the record and that a later lookup returns null:
@Test
public void whenDeleteById_thenAccountIsRemoved() {
accountMapper.deleteById(2L);
Account deletedAccount = accountMapper.selectOneById(2L);
assertNull(deletedAccount);
}
In practice, though, many applications avoid physical deletes of business data and prefer soft delete strategies so that records remain available for auditing or recovery.
5. Writing Queries With QueryWrapper
So far, we’ve used the mapper for direct CRUD operations. For more expressive reads, MyBatis-Flex provides QueryWrapper, a fluent API for building SQL conditions in Java code.
5.1. Multiple Conditions and Sorting
Let’s start with a query that combines filtering and sorting. This is a common pattern in application code, and QueryWrapper maintains good readability even when multiple conditions are involved:
@Test
public void whenQueryWithFilters_thenMatchingAccountsAreReturned() {
QueryWrapper queryWrapper = QueryWrapper.create()
.where(Account::getAge).ge(18)
.and(Account::getStatus).eq("ACTIVE")
.orderBy(column("age").desc());
List<Account> accounts = accountMapper.selectListByQuery(queryWrapper);
assertEquals(3, accounts.size());
assertEquals("emma", accounts.get(0).getUserName());
assertEquals("sarah", accounts.get(1).getUserName());
assertEquals("tom", accounts.get(2).getUserName());
}
In this case, we selected only adult accounts with an active status and sorted them by age in descending order. The resulting assertions made the ordering explicit and helped us verify that the generated query matched our intent.
5.2. Dynamic Queries
In many real search scenarios, some filters are optional. Instead of creating many query variants, we can build the QueryWrapper step by step and add each condition only when the corresponding parameter is present:
@Test
public void whenBuildingADynamicQuery_thenOnlyActiveAdultAccountsAreReturned() {
Integer minAge = 18;
String status = "ACTIVE";
QueryWrapper queryWrapper = QueryWrapper.create();
if (minAge != null) {
queryWrapper.where(Account::getAge).ge(minAge);
}
if (status != null) {
queryWrapper.and(Account::getStatus).eq(status);
}
queryWrapper.orderBy(column("id").asc());
List<Account> accounts = accountMapper.selectListByQuery(queryWrapper);
assertEquals(3, accounts.size());
assertEquals("sarah", accounts.get(0).getUserName());
assertEquals("emma", accounts.get(1).getUserName());
assertEquals("tom", accounts.get(2).getUserName());
}
This approach keeps the query logic flexible without sacrificing clarity.
5.3. Running Paged Queries
Pagination is a common way to split a large result set into smaller chunks, or pages, instead of loading every matching row at once. MyBatis-Flex supports it directly through the mapper, so we can request a specific page and page size without introducing a separate paging abstraction:
@Test
public void whenPaginating_thenPageMetadataAndRecordsAreReturned() {
QueryWrapper queryWrapper = QueryWrapper.create()
.where(Account::getAge).ge(18)
.orderBy(column("id").asc());
Page<Account> page = accountMapper.paginate(1, 2, queryWrapper);
assertEquals(2, page.getRecords().size());
assertEquals(3L, page.getTotalRow());
assertEquals(2L, page.getTotalPage());
}
Above, we paginated the filtered results and verified the returned records and page metadata. This is useful because pagination is about more than just limiting the number of rows. Often, we also need the total number of matching records and pages to build the surrounding application logic.
6. Conclusion
In this article, we built a small Spring Boot 4 project with MyBatis-Flex and used it to walk through the core persistence workflow. To that end, we configured an H2 datasource, defined an entity and mapper, and then verified the setup with JUnit 5 integration tests.
Furthermore, we saw how MyBatis-Flex supports both simple and more expressive data access patterns. Specifically, we used the built-in CRUD operations from BaseMapper, created filtered queries with QueryWrapper, and ran paged queries while checking both the returned records and the page metadata.
As always, the full code for this article is available over on GitHub.
















