SoFunction
Updated on 2025-03-06

The specific use of Mybatis enhanced version MyBatis-Flex

summary

This article introduces Mybatis-Flex, a framework for enhancing MyBatis. Compared with MyBatis-Plus, Mybatis-Flex provides some significant features, such as the support for conjunction table queries and the ability to charge in Mybatis-Plus is free in Mybatis-Flex. The article overviews the functional characteristics of MyBatis-Flex and introduces in-depth different solutions for conjunction table query.

Mybatis enhanced version: Mybatis-Plus (the most used, the old Mybatis enhancement framework, open source in 2016), Fluent-MyBatis (Mybatis enhancement framework developed by Alibaba Cloud, from Alibaba Cloud. Cloud Effect Product Team), Mybatis-Flex. In general, the more significant feature of Mybatis-Flex compared to Mybatis-Plus is that it has additional conjunction table query and free use of Mybatis-Flex that is charged in Mybatis-plus.

introduction

Mybatis-Flex is a framework for enhancing MyBatis functionality, providing a range of features and functions to make database operations more flexible and perform better. This article will introduce the functional characteristics, configuration methods, usage steps and some precautions of Mybatis-Flex.

Comparative Features

Function or Features MyBatis-Flex MyBatis-Plus Fluent-MyBatis
Basic addition, deletion, modification and search of entity
Pagination query
Total cache of pagination query
Pagination Query No SQL Resolution Design (Lighter, and Higher Performance)
Multi-table query: from Multi-table
Multi-table query: left join, inner join, etc.
Multi-table query: union, union all
Single primary key configuration
Multiple id generation strategies
Supports multiple primary keys and composite primary keys
TypeHandler configuration for fields
No other third-party dependencies except MyBatis (lighter)
Does QueryWrapper support RPC transmission under microservices projects unknown
Logical deletion
Optimistic lock
SQL Audit
Data Filling ✔️ (Product)
Data desensitization ✔️ (Product)
Field permissions ✔️ (Product)
Field encryption ✔️ (Product)
Dictionary writing back ✔️ (Product)
Db + Row
Entity Monitoring
Multi-data source support With other frameworks or fees
Does multi-data sources support Spring transaction management, such as @Transactional and TransactionTemplate
Does multi-data source support "non-Spring" projects
Multi-tenant
Dynamic table name
Dynamic Schema

Summarize: The significant feature of Mybatis-Flex compared to Mybatis-Plus is that it supports the joint table query function for free, and a fee is required in Mybatis-Plus. Since conjunction table query is widely used in daily development,Mybatis-FlexThis feature is provided to facilitate developers, so it performs well in this regard.

Configuration method

To configure Mybatis-Flex and use its features, follow these steps:

  • Import Mybatis-Flex's dependency library into the project:Add Mybatis-Flex dependencies to the project's build files (such as Maven or Gradle) so that its functionality can be used in the project.
  • Configure the data source and basic configuration of Mybatis:Configure database connection information and Mybatis basic configuration in the project's configuration file to ensure that Mybatis-Flex can connect to the database and work normally. This usually includes configuration items such as database URL, username, password, etc.
  • To define entity classes, you can use annotations to configure table names, field relationships, etc.:Create an entity class to map the table structure in the database. You can use the annotations provided by Mybatis-Flex to configure the mapping relationship between the entity class and the database table, including table names, field relationships, primary keys, etc. These annotations can help Mybatis-Flex to map when doing database operations.
  • Write a Mapper interface, inherit BaseMapper and define a custom query method:Create a Mapper interface and inherit the BaseMapper interface provided by Mybatis-Flex. BaseMapper already provides some common database operation methods, and you can then add custom query methods to this interface. These custom methods can leverage the query features of Mybatis-Flex to enable more complex database operations.
  • Use the features and functions provided by Mybatis-Flex to complete database operations:Use the defined Mapper interface in business logic to complete database operations. You can use the features provided by Mybatis-Flex, such as conjunction table query, condition query, etc. to complete database operations more conveniently and improve development efficiency.

Configuration steps

The following is configured and used in the projectMybatis-FlexGeneral steps:

  • Add toMybatis-FlexThe dependency library into the project's build file (e.g.Maven or Gradle)。
  • Configure data source andMybatisBasic configurations, such as connection database information, data source configuration, etc.
  • Define entity classes and use annotations to describe table names, field relationships, etc.
  • WrittenMapperInterface, inheritanceBaseMapperAnd add a custom query method.
  • Enable in the configuration fileMybatis-Flex, and configure the package scanning path of the entity class.
  • Use in codeMapperInterface methods to complete database operations, including adding, deleting, modifying and checking.

1. Add Mybatis-Flex dependency library to the project's build file (for example, Maven or Gradle):In the project's build file, add Mybatis-Flex dependencies to be able to use its features in the project.

<!-- Maven Dependency example -->
<dependency>
    <groupId></groupId>
    <artifactId>mybatis-flex</artifactId>
    <version>1.0.0</version>
</dependency>

2. Configure the data source and basic configuration of Mybatis:In the project's configuration file, configure the database connection information and the basic configuration of Mybatis so that Mybatis-Flex can connect to the database and work properly.

# Database connection configuration example=jdbc:mysql://localhost:3306/mydb
=root
=yourpassword

# Mybatis configuration example-location=classpath:

3. Define entity classes and use annotations to describe table names, field relationships, etc.:Create entity classes to map the table structure in the database, and use the annotations provided by Mybatis-Flex to configure the mapping relationship between entity classes and database tables.

import ;
import ;
import ;

@TableName("user")
public class User {

    @TableId(type = )
    private Long id;
    
    private String username;
    
    // Getters and setters
}

4. Write the Mapper interface, inherit BaseMapper and add custom query methods:Create a Mapper interface, inherit the BaseMapper interface provided by Mybatis-Flex, and then add a custom query method.

import ;
import ;
import ;

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

    // Add a custom query method, such as querying users based on username    User findByUsername(String username);
}

5. Enable Mybatis-Flex in the configuration file and configure the package scanning path of the entity class:Enable Mybatis-Flex in the Mybatis configuration file (such as ) and configure the package scanning path of the entity class.

<configuration>
    <!-- Configuration Mybatis-Flex Plugin -->
    <plugins>
        <plugin interceptor="">
            <!-- 可选的PluginConfiguration -->
        </plugin>
    </plugins>
    
    <!-- Configuration实体类的包扫描路径 -->
    <typeAliasesPackage></typeAliasesPackage>
    
    <!-- other Mybatis Configuration -->
</configuration>

6. Use the Mapper interface method in the code to complete database operations, including adding, deleting, modifying and checking:In the business logic code, the defined Mapper interface method is used to complete database operations, including adding, deleting, modifying and searching.

import ;
import ;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;
    
    public User getUserByUsername(String username) {
        return (username);
    }
    
    // Other business logic methods}

By following the detailed steps and code examples above to configure and use Mybatis-Flex, you will be able to better understand how to integrate the framework and perform database operations in your project. These examples will help you to make it easier to use the features of Mybatis-Flex in real development.

Things to note

When using Mybatis-Flex for development, you need to pay attention to the following points:

When developing with Mybatis-Flex, the following points need special attention to ensure that you can take advantage of the framework and perform database operations smoothly:

  • Familiar with the features and functions of Mybatis-Flex:Before starting a project, be sure to be familiar with the features and functions of the Mybatis-Flex framework. Understand the functions provided by the framework, such as conditional queries, associated queries, custom queries, etc., so that these features can be appropriately applied in actual development to meet business needs.

  • Correctly configure annotations in entity classes:When defining entity classes, use the annotations provided by Mybatis-Flex to correctly describe table names, field relationships and other information. These annotations will help the framework map entity class attributes to database tables, ensuring consistency when data manipulation is performed.

import ;
   
   @TableName("user")
   public class User {
       // Attribute declaration   }

Pay attention to the use of associated queries:When calling methods of the Mapper interface, especially when it comes to association queries, make sure you need to use the association query functionality provided by Mybatis-Flex. useselect***WithRelations()Method to trigger an association query to obtain the associated data.

Correctly configure to enable Mybatis-Flex and entity class scan paths:In the Mybatis configuration file, make sure the Mybatis-Flex plugin is enabled so that the framework works properly. At the same time, configure the package scanning path of the entity class so that the framework can find and correctly process the annotations of the entity class.

<configuration>
       <!-- Configuration Mybatis-Flex Plugin -->
       <plugins>
           <plugin interceptor="">
               <!-- 可选的PluginConfiguration -->
           </plugin>
       </plugins>
       
       <!-- Configuration实体类的包扫描路径 -->
       <typeAliasesPackage></typeAliasesPackage>
       
       <!-- other Mybatis Configuration -->
   </configuration>
  • A deep understanding of complex operational solutions:When it comes to complex multi-table queries, associations and other operations, you need to have a deeper understanding of the solutions provided by Mybatis-Flex. Read official documents, view sample code, or try to simulate operations in different scenarios to better grasp the use of the framework.

By familiarizing yourself with features, correctly configuring entity class annotations, paying attention to association queries, correctly configuring Mybatis-Flex and entity class scanning paths, and in-depth understanding of complex operational solutions, you will be able to better apply the Mybatis-Flex framework, improve development efficiency and complete database operations smoothly.

Relations annotation

In the MyBatis-Flex framework, in order to handle different association query scenarios, four different Relations annotations are provided. These annotations can be used to configure the association relationship between entity classes so that the associated data can be obtained when performing database queries. Here is a detailed explanation of these annotations and an example of how to use them in actual code:

RelationOneToOne (one-to-one relationship):Used to describe a one-to-one relationship between two entity classes. Usually in two entity classes, one class refers to an instance of the other. This annotation is used to configure the associated field and relationship types.

@TableName("user")
public class User {
    // Attribute declaration    
    @RelationOneToOne(selfField = "id", targetField = "userId")
    private UserProfile userProfile;
}

RelationOneToMany (one-to-many relationship):Used to describe a one-to-many relationship between an entity class and multiple other entity classes. In the main entity class, use the collection attribute to refer to multiple instances of other entity classes.

@TableName("user")
public class User {
    // Attribute declaration    
    @RelationOneToMany(selfField = "id", targetField = "userId")
    private List<Order> orders;
}

RelationManyToOne (Many-to-One Relationship):Used to describe a many-to-one relationship in which multiple entity classes refer to the same entity class. In multiple entity classes, use a single attribute to refer to an instance of the same entity class.

@TableName("order")
   public class Order {
       // Attribute declaration       
       @RelationManyToOne(selfField = "userId", targetField = "id")
       private User user;
   }

RelationManyToMany (many-to-many relationship):Used to describe many-to-many relationships between multiple entity classes. This relationship is usually required through intermediate tables.

@TableName("user")
public class User {
    // Attribute declaration    
    @RelationManyToMany(joinTable = "user_role", joinSelfColumn = "user_id", joinTargetColumn = "role_id")
    private List<Role> roles;
}

After configuring entity class association relationships using these Relations annotations, you need to call the correspondingselect***WithRelations()Methods to make the Relations annotation take effect. Otherwise, MyBatis-Flex will automatically ignore these Relations annotations.

For example, for the above entity class that has associated relationships configured, the following is how to use it in the Mapper interfaceselectListWithRelations()Example of a method to query data:

@Mapper
public interface UserMapper extends BaseMapper<User> {
    
    List<User> selectUsersWithRelations();
}

With this configuration, you can better understand and apply the association annotations provided in the MyBatis-Flex framework and get the associated data during database queries.

Summarize

Mybatis-Flex is a framework for enhancing MyBatis, providing a variety of features and functions to optimize database operations. This article briefly introduces the features of Mybatis-Flex and explains in detail how to configure and use its features. Through reasonable configuration and use, developers can more flexibly perform database operations and improve development efficiency and code quality.

References

  • Mybatis-Flex official website
  • MyBatis official website

This is the article about the specific use of Mybatis enhanced version of MyBatis-Flex. For more related content on MyBatis-Flex, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!