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@TableName
Annotation specifies the corresponding database table name, use@TableId
Annotation specifies the primary key field. Use on the Mapper interface@Mapper
Annotation 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 usedinsert
The method, the sample code is as follows:
User user = new User(); ("Tom"); ("123456"); (18); UserMapper userMapper = (); int result = (user); if (result > 0) { ("Insert successfully"); }
2.2 Query operation
Query operation can be usedselectById
、selectList
、selectPage
Such as the example code is as follows:
UserMapper userMapper = (); // Query by IDUser user = (1L); // Query according to the conditionsLambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>(); (User::getUsername, "Tom"); List<User> userList = (queryWrapper); // Pagination queryPage<User> page = new Page<>(1, 10); LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>(); (User::getAge); IPage<User> resultPage = (page, queryWrapper); List<User> userList = ();
2.3 Update operation
Update operation can be usedupdateById
The method, the sample code is as follows:
User user = new User(); (1L); ("Jerry"); ("654321"); (20); UserMapper userMapper = (); int result = (user); if (result > 0) { ("Update Successfully"); }
2.4 Delete operation
Delete operation can be useddeleteById
、deleteBatchIds
、delete
Such as the example code is as follows:
UserMapper userMapper = (); //Delete by IDint result = (1L); if (result > 0) { ("Delete successfully"); } //Delete according to the conditionsLambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>(); (User::getUsername, "Tom"); int result = (queryWrapper); if (result > 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 useBaseMapper
ProvidedselectList
、selectById
、insert
、updateById
、deleteById
Overloaded version of etc., pass inWrapper
Objects andRowBounds
Objects are customized for querying and pagination.
UserMapper userMapper = (); // Custom SQL queryLambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>(); (User::getId, User::getUsername) .orderByAsc(User::getAge); List<User> userList = (queryWrapper, new RowBounds(0, 10)); // Custom SQL InsertUser user = new User(); ("CustomUser"); ("password"); (25); int result = (user, new InsertWrapper<User>().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<User>
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@TableLogic
Annotation identifier deletes flag bit field and uses it on the Mapper interface@Mapper
AnnotatedlogicDelete
Properties 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@TableLogic
Annotation specifies the delete flag field and deleted value, used on the Mapper interface@Mapper
AnnotatedlogicDelete
Properties enable logical deletion. This will be useddeleteById
、deleteBatchIds
、delete
Logical 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@Version
Annotation identifies the version number field and use it on the Mapper interface@Mapper
AnnotatedoptimisticLocker
Properties 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@Version
Annotation identification version number field, used on the Mapper interface@Mapper
AnnotatedoptimisticLocker
Properties enable optimism locking. This will be usedupdateById
Optimistic lock update operation is carried out by other methods.
3.4 Global Interceptor
MyBatis-Plus provides a global interceptor function, which can be implemented byInterceptor
Interface 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); } }
accomplishInterceptor
interface and use@Intercepts
Annotation identifies the method and parameter type of intercept. existintercept
Perform 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-plus
Configuration in the tagconfiguration
Tags, inconfiguration
Configuration in the taginterceptors
Tags, ininterceptors
Configure 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-generator
The global configuration, data source configuration, package information configuration, and policy configuration of the code generator are configured in the tag. existglobal-config
The output directory, author information and whether to automatically open the generated folder in the tag. existdata-source
Configure database connection information in the tag. existpackage-info
Configure package name information in the tag. existstrategy
The 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!