SoFunction
Updated on 2025-04-04

Mybatis-plus encapsulation implementation of single table operations

MyBatis-Plus is an enhancement tool based on MyBatis. It provides rich functions such as CRUD operations and pagination queries, greatly simplifying developers' database operations. This article will introduce the single table operations that have been written by MyBatis-Plus in detail and provide some expansion content.

1. Introduction

Before performing single table operations, we need to define an entity class and the corresponding Mapper interface. Here is a simple entity class and Mapper interface example:

@Data
@TableName("user")
public class User {
    @TableId(type = )
    private Long id;
    private String username;
    private String password;
    private Integer age;
}

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

Use on entity classes@TableNameAnnotation specifies the corresponding database table name, use@TableIdAnnotation specifies the primary key field. Use on the Mapper interface@MapperAnnotation identifies that the interface is a Mapper interface and inherits itBaseMapper<User>, so that you can directly use the CRUD operation method provided by MyBatis-Plus.

2. Single table operation

2.1 Insert operation

Insert operation can be usedinsertThe method, the sample code is as follows:

User user = new User();
("Tom");
("123456");
(18);

UserMapper userMapper = ();
int result = (user);
if (result &gt; 0) {
    ("Insert successfully");
}

2.2 Query operation

Query operation can be usedselectByIdselectListselectPageSuch as the example code is as follows:

UserMapper userMapper = ();

// Query by IDUser user = (1L);

// Query according to the conditionsLambdaQueryWrapper&lt;User&gt; queryWrapper = new LambdaQueryWrapper&lt;&gt;();
(User::getUsername, "Tom");
List&lt;User&gt; userList = (queryWrapper);

// Pagination queryPage&lt;User&gt; page = new Page&lt;&gt;(1, 10);
LambdaQueryWrapper&lt;User&gt; queryWrapper = new LambdaQueryWrapper&lt;&gt;();
(User::getAge);
IPage&lt;User&gt; resultPage = (page, queryWrapper);
List&lt;User&gt; userList = ();

2.3 Update operation

Update operation can be usedupdateByIdThe method, the sample code is as follows:

User user = new User();
(1L);
("Jerry");
("654321");
(20);

UserMapper userMapper = ();
int result = (user);
if (result &gt; 0) {
    ("Update Successfully");
}

2.4 Delete operation

Delete operation can be useddeleteByIddeleteBatchIdsdeleteSuch as the example code is as follows:

UserMapper userMapper = ();

//Delete by IDint result = (1L);
if (result &gt; 0) {
    ("Delete successfully");
}

//Delete according to the conditionsLambdaQueryWrapper&lt;User&gt; queryWrapper = new LambdaQueryWrapper&lt;&gt;();
(User::getUsername, "Tom");
int result = (queryWrapper);
if (result &gt; 0) {
    ("Delete successfully");
}

3. Expand content

In addition to the official basic CRUD operation, MyBatis-Plus also provides many other functions and extensions. The following are some commonly used extensions:

3.1 Custom SQL

If you need to customize SQL statements, you can useBaseMapperProvidedselectListselectByIdinsertupdateByIddeleteByIdOverloaded version of etc., pass inWrapperObjects andRowBoundsObjects are customized for querying and pagination.

UserMapper userMapper = ();

// Custom SQL queryLambdaQueryWrapper&lt;User&gt; queryWrapper = new LambdaQueryWrapper&lt;&gt;();
(User::getId, User::getUsername)
            .orderByAsc(User::getAge);
List&lt;User&gt; userList = (queryWrapper, new RowBounds(0, 10));

// Custom SQL InsertUser user = new User();
("CustomUser");
("password");
(25);
int result = (user, new InsertWrapper&lt;User&gt;().setSql("INSERT INTO user(username, password, age) VALUES(#{username}, #{password}, #{age})"));

// Custom SQL updatesUser updateUser = new User();
(1L);
("UpdatedUser");
("updatedPassword");
int result = (updateUser, new UpdateWrapper&lt;User&gt;

3.2 Logical deletion

MyBatis-Plus provides logical deletion function, which can be implemented by configuring entity classes and database table fields. Logical deletion refers to setting the delete flag of a record in the database to deleted, rather than physically deleting the record. This can avoid accidentally deleting data, and it can also meet some special needs, such as data recovery, data audit, etc.

To use the logical deletion function, you need to use it on the entity class@TableLogicAnnotation identifier deletes flag bit field and uses it on the Mapper interface@MapperAnnotatedlogicDeleteProperties enable logical deletion. The sample code is as follows:

@Data
@TableName("user")
@TableLogic(value = "deleted", delval = "1")
public class User {
    @TableId(type = )
    private Long id;
    private String username;
    private String password;
    private Integer age;
    private Integer deleted;
}

@Mapper(logicDelete = true)
public interface UserMapper extends BaseMapper<User> {
}

Use on entity classes@TableLogicAnnotation specifies the delete flag field and deleted value, used on the Mapper interface@MapperAnnotatedlogicDeleteProperties enable logical deletion. This will be useddeleteByIddeleteBatchIdsdeleteLogical deletion operation is performed by other methods.

3.3 Optimistic lock

MyBatis-Plus provides optimistic locking functionality, which can be implemented by configuring entity classes and database table fields. Optimistic locking is a concurrency control strategy that assumes that multiple transactions will not conflict when executed concurrently, and each transaction will verify that the data of its operation has been modified by other transactions when committing. If the data is found to have been modified, the current transaction will be rolled back, avoiding the problem of data inconsistency.

To use the optimistic lock function, you need to use it on the entity class@VersionAnnotation identifies the version number field and use it on the Mapper interface@MapperAnnotatedoptimisticLockerProperties enable optimism locking. The sample code is as follows:

@Data
@TableName("user")
@Version
public class User {
    @TableId(type = )
    private Long id;
    private String username;
    private String password;
    private Integer age;
    private Integer version;
}

@Mapper(optimisticLocker = true)
public interface UserMapper extends BaseMapper<User> {
}

Use on entity classes@VersionAnnotation identification version number field, used on the Mapper interface@MapperAnnotatedoptimisticLockerProperties enable optimism locking. This will be usedupdateByIdOptimistic lock update operation is carried out by other methods.

3.4 Global Interceptor

MyBatis-Plus provides a global interceptor function, which can be implemented byInterceptorInterface custom interceptors and register interceptors in the configuration file. The global interceptor can intercept all SQL statements and perform some custom operations before and after SQL execution, such as logging, permission verification, etc.

The sample code is as follows:

@Component
@Intercepts({@Signature(type = , method = "update", args = {, })})
public class MyInterceptor implements Interceptor {
    @Override
    public InterceptResult intercept(Invocation invocation) throws Throwable {
        // Do some custom operations before SQL execution        ("Before SQL: " + ());

        // Execute SQL statements        Object result = ();

        // Do some custom operations after SQL execution        ("After SQL: " + ());

        return (result);
    }
}

accomplishInterceptorinterface and use@InterceptsAnnotation identifies the method and parameter type of intercept. existinterceptPerform custom operations in the method and use()Execute SQL statements. Last return(result)Indicates that the interceptor is executed successfully.

Register the interceptor in the configuration file, the sample code is as follows:

<mybatis-plus>
    <configuration>
        <interceptors>
            <interceptor class=""/>
        </interceptors>
    </configuration>
</mybatis-plus>

existmybatis-plusConfiguration in the tagconfigurationTags, inconfigurationConfiguration in the taginterceptorsTags, ininterceptorsConfigure custom interceptor classes in the tag.

3.5 Code Generator

MyBatis-Plus provides code generator functions, which can automatically generate codes such as entity classes, Mapper interfaces, Service interfaces and Controller interfaces through configuration files. Code generators can greatly improve development efficiency and avoid repeated labor.

The sample code is as follows:

<mybatis-plus-generator>
    <global-config>
        <output-dir>D:\code\mybatis-plus-generator\src\main\java</output-dir>
        <author>zhangsan</author>
        <open>false</open>
    </global-config>
    <data-source>
        <url>jdbc:mysql://localhost:3306/mybatis_plus</url>
        <username>root</username>
        <password>123456</password>
        <driver-class-name></driver-class-name>
    </data-source>
    <package-info>
        <module-name>user</module-name>
        <parent></parent>
    </package-info>
    <strategy>
        <table-prefix>t_</table-prefix>
        <entity-lombok-model>true</entity-lombok-model>
        <rest-controller-style>true</rest-controller-style>
        <controller-mapping-hyphen-style>true</controller-mapping-hyphen-style>
        <include>t_user</include>
    </strategy>
</mybatis-plus-generator>

existmybatis-plus-generatorThe global configuration, data source configuration, package information configuration, and policy configuration of the code generator are configured in the tag. existglobal-configThe output directory, author information and whether to automatically open the generated folder in the tag. existdata-sourceConfigure database connection information in the tag. existpackage-infoConfigure package name information in the tag. existstrategyThe table name prefix is ​​configured in the tag, whether the entity class uses Lombok annotation, whether the Controller interface uses RESTful style and the table name to be generated.

After running the code generator, codes such as entity classes, Mapper interfaces, Service interfaces, and Controller interfaces will be automatically generated.

4. Summary

MyBatis-Plus is a very powerful ORM framework that provides rich functions such as CRUD operations and pagination queries, and also provides many other functions and extensions, such as custom SQL, logical deletion, optimistic locking, global interceptors and code generators. Using MyBatis-Plus can greatly improve development efficiency and can also meet some special needs.

This is the article about the packaging implementation of Mybatis-plus for single-table operations. For more related contents of Mybatisplus for single-table operations, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!