Advanced MyBatis-Plus Features: Type Handlers, Auto-Filling, Optimistic Locking, and Multi-DataSource Configuration

1. Field Type Handlers

In certain scenarios, entity classes may utilize Map collections to receive data from frontend applications. However, when storing this data in databases, JSON format is often used, which本质上 is a string stored as a VARCHAR type. Field type handlers facilitate the conversion between Map types in entity classes and VARCHAR types in databases. Example:
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(autoResultMap = true)
public class UserProfile extends Model {
    private Long id;
    private String fullName;
    private Integer years;
    private String emailAddress;
    private GenderType gender;
    private Integer accountStatus;
    @TableField(typeHandler = JsonMapTypeHandler.class)
    private Map preferences;  // Map type attribute
}
This implementation enables seamless conversion between Map objects and JSON strings during database operations.

2. Field Auto-Filling

This feature is particularly useful for managing timestamp fields automatically.
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName(autoResultMap = true)
public class UserProfile {
    @TableId
    private Long id;
    private String fullName;
    private Integer years;
    private String emailAddress;
    private Integer accountStatus;
    private GenderType gender;
    @TableField(fill = FieldFill.INSERT)
    private Date registrationDate;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date lastModified;
}
Implement a custom auto-fill handler:
@Component
public class TimestampHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        setFieldValByName("registrationDate", new Date(), metaObject);
        setFieldValByName("lastModified", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        setFieldValByName("lastModified", new Date(), metaObject);
    }
}

3. Optimistic Locking

Implementation steps: 1. Add a version field to the database table (INT type, default value 1) 2. Add the corresponding property to the entity class and annotate it with @Version
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserProfile {
    private Long id;
    private String fullName;
    private Integer years;
    private String emailAddress;
    @Version
    private Integer recordVersion;
}
3. Configure the interceptor to add version control to all modification SQL statements Optimistic locking allows one request to modify data while another request can query it simultaneously. During modification, the system checks if the version number has changed. If it has, another request has already modified the data, and the current modification fails. If the version remains unchanged, the modification proceeds successfully.
@Configuration
public class DatabaseConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}

4. Multi-DataSource Configuration

4.1. Add Dependency

    com.baomidou
    dynamic-datasource-spring-boot-starter
    3.5.0

4.2. Configuration File (application.yml)
spring:
  datasource:
    dynamic:
      primary: primary
      strict: false
      datasource:
        primary:
          username: admin
          password: password
          url: jdbc:mysql://localhost:3306/main_db?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
          driver-class-name: com.mysql.cj.jdbc.Driver
        secondary:
          username: admin
          password: password
          url: jdbc:mysql://localhost:3306/secondary_db?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
          driver-class-name: com.mysql.cj.jdbc.Driver
4.3. Create Multiple Services with @DS Annotation
@Service
@DS("primary")
public class PrimaryUserProfileService extends ServiceImpl implements UserProfileService {
}

@Service
@DS("secondary")
public class SecondaryUserProfileService extends ServiceImpl implements UserProfileService {
}

5. Reverse Engineering

Use the MyBatisX plugin for reverse engineering operations: 1. Connect to the database using IDEA 2. Right-click on a table and select MybatisX-Generator 3. Fill in the required information to generate the code

Tags: mybatis-plus java database Type Handlers Auto-Filling

Posted on Thu, 07 May 2026 15:23:20 +0000 by 01hanstu