eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Spring Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 30% off until 31st March, 2026

>> EXPLORE ACCESS NOW

Partner – Diagrid – NPI EA (cat= Testing)
announcement - icon

In distributed systems, managing multi-step processes (e.g., validating a driver, calculating fares, notifying users) can be difficult. We need to manage state, scattered retry logic, and maintain context when services fail.

Dapr Workflows solves this via Durable Execution which includes automatic state persistence, replaying workflows after failures and built-in resilience through retries, timeouts and error handling.

In this tutorial, we'll see how to orchestrate a multi-step flow for a ride-hailing application by integrating Dapr Workflows and Spring Boot:

>> Dapr Workflows With PubSub

Course – Spring Sale 2026 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 30% off until 31st March, 2026

>> EXPLORE ACCESS NOW

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.

Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Spring Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 30% off until 31st March, 2026

>> EXPLORE ACCESS NOW

Course – Spring Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 30% off until 31st March, 2026

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)
guest
0 Comments
Oldest
Newest
Inline Feedbacks
View all comments