DevBackend TechHub
DevBackend TechHub
Java

MyBatis-Plus Masterclass: Spring Boot 3 & Lambda Queries

Master MyBatis-Plus with Spring Boot 3. Learn Lambda wrappers, pagination, and performance tuning. Compare with JPA & raw MyBatis. Download the code today.

#Java#SQL

I still remember the afternoon I spent staring at a 500-line XML mapper file, trying to track down why a simple dynamic WHERE clause was generating invalid SQL. Or the time I spent debugging a Hibernate entity that was executing 500 individual SELECT statements for a single page of data—the infamous N+1 problem. These are the moments when you realize that while raw MyBatis gives you total control, and JPA offers high-level abstraction, both come with a steep tax on developer productivity.

Enter MyBatis-Plus. In the crowded landscape of the Java ORM framework ecosystem, MyBatis-Plus positions itself not as a replacement, but as an "enhanced toolkit" that bridges the gap. It strips away the repetitive DAO layer abstraction code for standard CRUD operations while keeping the flexibility of writing custom SQL when you need it. In this masterclass, we will move beyond the basics. We will look at Spring Boot 3 specific integration pitfalls, deep-dive into the lambda query wrappers for type-safe dynamic SQL, and compare performance metrics against JPA to help you make an informed architectural decision.

Close-up of JavaScript code on a computer screen, showing web development programming.

Setting Up MyBatis-Plus with Spring Boot 3: Beyond Basic Dependencies

Many developers upgrade to Spring Boot 3 assuming the standard starter works unchanged. It doesn’t. The auto-configuration mechanisms have shifted, and using the wrong artifact can lead to confusing bean creation failures.

Resolving Auto-Configuration Failures in Spring Boot 3.x

If you are migrating from Spring Boot 2, the first hurdle is the dependency. For Spring Boot 2, you would traditionally use mybatis-plus-boot-starter. However, for Spring Boot 3, which runs on Jakarta EE 9+ (formerly Java EE), you must use the dedicated mybatis-plus-spring-boot3-starter. Using the older starter results in a version mismatch because the underlying Spring JDBC dependencies are incompatible with the new namespace.

I’ve seen this error repeatedly in CI/CD pipelines:

Caused by: java.lang.NoClassDefFoundError: javax/sql/DataSource
    at com.baomidou.mybatisplus.spring.boot.autoconfigure.MybatisPlusAutoConfiguration...

This happens because Spring Boot 3 expects jakarta.sql.DataSource, while the old starter tries to wire up javax.sql. To fix this, update your pom.xml to the v3 starter:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
    <version>3.5.5</version>
</dependency>

Additionally, ensure your application.yml is configured correctly. Spring Boot 3 is stricter about configuration properties. A common pitfall is forgetting that MyBatis-Plus properties are now nested under mybatis-plus rather than just mybatis. Here is the correct structure for a MySQL setup:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb
    username: root
    password: secret
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis-plus:
  configuration:
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      id-type: auto

Note: Version compatibility is key. MyBatis-Plus 3.5.5+ is recommended for Spring Boot 3.2+ to ensure smooth integration with the latest Jakarta packages.

Entity Mapping & The BaseMapper Hierarchy

Once the setup is clean, the beauty of MyBatis-Plus lies in how minimal your data access object (DAO) needs to be. You don't write XML files for basic operations. Instead, you define an entity class and a mapper interface that extends BaseMapper<T>.

Entity mapping is handled via annotations. The @TableName annotation maps your Java class to a database table, and @TableId specifies the primary key strategy.

@Data
@TableName("user")
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String username;
    private String email;
}

The corresponding Mapper is remarkably short. By extending BaseMapper<User>, you instantly inherit methods like insert, deleteById, selectById, and updateById.

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

In your Service layer, you simply inject this mapper using Spring dependency injection. There is no boilerplate implementation code required for basic CRUD. This is where the productivity boost comes from—what used to take three classes (Mapper interface, XML file, DAO implementation) now takes just one interface.

A close-up view of PHP code displayed on a computer screen, highlighting programming and development concepts.

Mastering the Lambda Query Wrapper: Syntax & Deep Dive

While BaseMapper covers simple CRUD, real-world applications require complex filtering. This is where the MyBatis-Plus Lambda Query Wrapper shines. It allows you to construct type-safe dynamic SQL conditions using method references, eliminating the risk of spelling errors in column names.

LambdaQueryWrapper vs QueryWrapper: Under the Hood

There are two main wrapper types: QueryWrapper (string-based) and LambdaQueryWrapper (type-safe).

In QueryWrapper, you pass column names as strings: wrapper.eq("username", "admin"); If you rename the database column from username to user_name but forget to update the string, the application fails at runtime with a SQL syntax error. It’s a fragile pattern.

In LambdaQueryWrapper, you use method references: wrapper.eq(User::getUsername, "admin"); The compiler verifies that User has a getUsername method. If you rename the field, the code won't compile. This is a significant improvement for maintainability in large teams.

Under the hood, MyBatis-Plus uses a combination of reflection and a cache to resolve the lambda expression to the corresponding database column name. It stores a mapping of method references to column strings in a static map when the class is loaded. This avoids the performance penalty of full reflection on every query execution, though there is a minor overhead during the initial setup.

Best Practice: Avoid deeply nested lambda chains. While the syntax is readable, extremely complex nested conditions can become hard to debug. If a query requires more than 3-4 levels of nesting, consider breaking it into a custom XML mapper method for clarity and performance.

Practical Examples: Complex Conditions & Updates

Let’s look at a practical scenario: finding all users who are either active OR (VIP and have a verified email).

LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(User::getStatus, "ACTIVE")
       .or(w -> w.eq(User::getVipLevel, 5)
                 .and().eq(User::getEmailVerified, true));

List<User> users = userMapper.selectList(wrapper);

For updates, you can use LambdaUpdateWrapper to target specific fields without loading the entire entity into memory. This is more efficient than calling updateById on a fully populated object.

LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
updateWrapper.eq(User::getId, 101L)
             .set(User::getVipLevel, 10)
             .set(User::getUpdatedAt, LocalDateTime.now());

userMapper.update(null, updateWrapper);

The Gotcha: A common logical error is mixing up the chaining of and and or. In the example above, the or clause applies to the entire sub-wire. If you accidentally place .and() after the or block without proper grouping, you might think you're querying (A OR B) AND C, but the parser might interpret it differently if the nesting isn't explicit. Always use parentheses via nested lambdas (w -> ...) when mixing boolean operators to ensure the SQL WHERE clause logic matches your intent.

Advanced Features: Pagination, Logical Delete & Interceptors

MyBatis-Plus is not just about queries; it’s about managing the entire data lifecycle with minimal code. Two features that save production headaches are automatic pagination and logical deletion.

Configuring the Pagination Plugin Correctly

MyBatis does not support pagination out of the box. MyBatis-Plus provides a plugin that rewrites your SQL to include LIMIT and OFFSET. However, you must configure the MybatisPlusInterceptor correctly for it to work.

Create a configuration class:

@Configuration
public class MyBatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // Add the pagination interceptor
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

Crucial Detail: If you are using PostgreSQL or Oracle, change DbType.MYSQL to DbType.POSTGRE_SQL or DbType.ORACLE. The dialect matters because the limit/offset syntax differs. For example, Oracle 12c+ uses OFFSET ... ROWS, while older versions use ROWNUM. Using the wrong DB type can result in SQL syntax errors that are very difficult to debug.

Using it in your service is straightforward:

Page<User> page = new Page<>(1, 10); // Page 1, Size 10
Page<User> result = userMapper.selectPage(page, null);
return result.getRecords();

The plugin automatically executes a COUNT query first, then the data query with the limit/offset parameters, ensuring you get accurate total page counts.

Logical Delete & Optimistic Locking Strategies

In production environments, physical DELETE statements are rarely appropriate for critical data. Instead, we use logical delete. MyBatis-Plus supports this via the @TableLogic annotation.

Add a field to your entity:

@TableLogic
private Integer deleted; // 0 for active, 1 for deleted

Now, when you call userMapper.deleteById(1), MyBatis-Plus automatically converts it to: UPDATE user SET deleted = 1 WHERE id = 1 AND deleted = 0;

All subsequent select queries will automatically append AND deleted = 0 to their WHERE clause. This requires zero manual code in your queries.

For concurrent updates, optimistic locking prevents race conditions. Use the @Version annotation on a field (e.g., version):

@Version
private Integer version;

Register the OptimisticLockerInnerInterceptor in your config (alongside the pagination one). When you update a record, MyBatis-Plus adds AND version = ? to the UPDATE statement and increments the version. If two threads try to update the same row simultaneously, the second one will fail because the version in the database no longer matches, allowing you to detect and retry or fail gracefully.

MyBatis-Plus vs JPA & MyBatis: When to Choose Which?

Choosing the right ORM is a strategic decision. MyBatis-Plus sits in the middle ground. Let’s compare it with its main contenders.

Performance Benchmarks & SQL Generation Comparison

In terms of raw CRUD performance, MyBatis-Plus is essentially equivalent to raw MyBatis because it generates the same direct SQL statements. There is almost no overhead for basic operations compared to standard MyBatis.

However, when compared to JPA (Hibernate), the dynamic SQL capabilities of MyBatis-Plus can outperform Hibernate in complex, multi-condition queries. Hibernate generates Criteria or JPQL queries that can sometimes be less optimized, especially when the query shape changes frequently. MyBatis-Plus gives you the control of MyBatis (you see the exact SQL) but the convenience of a wrapper.

Trade-off: JPA provides a rich object-oriented domain model and automatic relationship management (fetch joins, etc.). MyBatis-Plus does not manage relationships automatically. If you have a deeply nested object graph with lazy-loading requirements, JPA is superior. If you have wide tables and complex reporting queries, MyBatis-Plus is often faster and easier to tune.

Migration Cost Consideration: Moving from JPA to MyBatis-Plus is a significant refactor. You lose automatic relationship mapping and must write explicit join SQL or handle mapping in the service layer. Moving from raw MyBatis to MyBatis-Plus is much cheaper—often just a dependency change and minor annotation updates.

Handling N+1 Select Problems & Multiple Data Sources

Since MyBatis-Plus does not use a first-level cache like Hibernate by default, N+1 problems can occur if you load a list of parents and then query children individually. The strategy here is eager loading via joins or batch fetching.

Unlike Hibernate, which has FetchType.EAGER, MyBatis-Plus relies on you to write the join. For example, to load Orders with their Users, you would use a custom XML mapper with a LEFT JOIN or use the selectList with a specific result map. MyBatis-Plus provides @ResultMap and association handling, but it is manual.

For multiple data sources, MyBatis-Plus integrates well with the dynamic-datasource-spring-boot-starter. You can annotate specific Mappers or Services with @DS("master") or @DS("slave") to switch connections dynamically. This is a powerful feature for read/write separation. In contrast, JPA requires more complex configuration to swap EntityManagerFactory beans.

Production Readiness: Code Generation & Custom Templates

For large projects with hundreds of tables, writing entities and mappers manually is unsustainable. MyBatis-Plus’s code generator is a productivity multiplier.

Customizing the FastAutoGenerator

The generator can scan your database schema and produce the Entity, Mapper, Service, and Controller layers. You can customize the output using Freemarker or Velocity templates.

FastAutoGenerator.create("jdbc:mysql://localhost:3306/mydb", "root", "root")
    .globalConfig(b -> {
        b.author("YourName").fileOverride(false);
        b.outputDir("/path/to/project/src/main/java");
    })
    .packageInfo(b -> b.parent("com.yourcompany").moduleName("user"))
    .strategy(b -> {
        b.naming(column -> SensitiveUtil.name(column)).format("user%s");
        b.addInclude("user", "order"); // Only generate for these tables
    })
    .execute();

You can override the default templates to add Lombok annotations or specific Javadoc tags. This ensures that your generated code matches your team’s coding standards without manual cleanup.

Automating Primary Keys & ID Strategies

In distributed systems, auto-increment integers are not safe. MyBatis-Plus supports Snowflake ID generation out of the box. You can configure the IdentifierGenerator to use Snowflake, which generates a unique, time-ordered 64-bit ID.

// In configuration or via @TableId(type = IdType.ASSIGN_ID)
// This defaults to Snowflake ID in recent versions if no type is specified

You can also implement custom IdentifierGenerator interfaces if you need UUIDs or specific business logic for ID generation. For most distributed applications, the built-in Snowflake implementation is robust and requires zero configuration.

FAQ

What is the difference between MyBatis and MyBatis-Plus? MyBatis is the core framework that requires you to write XML or annotation-based SQL mapping for every operation. MyBatis-Plus is an extension that adds BaseMapper for automatic CRUD, code generation, and advanced query wrappers, without altering the core MyBatis behavior. It’s an "enhancement" layer, not a replacement.

Does MyBatis-Plus support multiple data sources? Yes. It integrates seamlessly with the dynamic-datasource-spring-boot-starter. You can switch data sources at the method level using annotations like @DS("read"). However, be cautious with complex distributed transactions; standard @Transactional may not span across different data sources without additional configuration like Seata.

How to handle N+1 select problem in MyBatis-Plus? Unlike JPA, MyBatis-Plus does not auto-fetch associated entities. To mitigate N+1 issues, you should use LEFT JOIN in your custom XML mapper queries or use the selectList method with explicit batch loading if you must fetch related data. Avoid calling a separate selectById for each item in a loop.

Is MyBatis-Plus compatible with Java 17/21? Yes. MyBatis-Plus 3.5.3 and later versions are fully compatible with Java 17 and Java 21. There are no specific configuration changes required for the module system, as MyBatis-Plus does not rely on legacy internal APIs that were restricted in newer JDKs. Just ensure you are using the Spring Boot 3 starter if you are on Java 17+.

Conclusion

MyBatis-Plus offers a pragmatic middle path in the Java persistence world. It eliminates the boilerplate of standard MyBatis while avoiding the "black box" complexity of JPA for complex queries. The shift to Spring Boot 3 has solidified its position, with specific starters ensuring smooth integration with the modern Jakarta ecosystem.

When selecting an ORM, match it to your project’s complexity. For CRUD-heavy applications with complex reporting needs, MyBatis-Plus’s lambda wrappers and logical delete features provide a significant productivity boost. For highly relational domain models with deep object graphs, JPA might still be the better fit. Regardless of your choice, always tune your pagination and use logical deletion to maintain data integrity in production environments.

Ready to try it out? Check out the official MyBatis-Plus GitHub repository for the latest version updates and community-driven examples. You can also find pre-configured Spring Boot 3 + MyBatis-Plus starter templates on popular code-hosting platforms to get a head start on your next project.

Related Posts