Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize automatic update, soft deletion and optimistic lock operation in MyBatisPlus

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you how MyBatisPlus to achieve automatic update, soft deletion, optimistic lock operation, I hope you will gain something after reading this article, let's discuss it together!

Getting started

Steps

Create database, data table

Import maven dependencies using SpringBoot

Mysql mysql-connector-java 8.0.21 org.projectlombok lombok 1.18.12 com.baomidou mybatis-plus-boot-starter 3.3.2

After using mybatis-plus (different from mybatis traditional method entity-dao (connect mybatis, configure mapper.xml file)-service-controller)

Entity class:

@ Datapublic class User {/ * primary key ID * / @ TableId (value = "id", type = IdType.AUTO) private Long id; / * name * / private String name; / * * Age * / private Integer age; / * * mailbox * / private String email;}

Mapper interface

/ / the corresponding Mapper inherits the basic class BaseMapper@Repositorypublic interface UserMapper extends BaseMapper {/ / General CRUD operation parent class has been written}

Note that we need to scan all interfaces under our mapper package on the main startup class

@ MapperScan ("com.mybatis.mybatis_plus.mapper")

You can test in a test class:

@ Autowired private UserMapper userMapper; @ Test void contextLoads () {List userList = userMapper.selectList (null); userList.forEach (System.out::println);}

Automatic update

All database tables: gmt_create, gmt_modified almost all tables should be configured! And need to be automated!

1. Add fields gmt_create, gmt_modified and type datetime to the table.

2. Synchronize the entity class and add notes to the field attributes of the entity class.

@ TableField (fill = FieldFill.INSERT) private Date gmtCreate; @ TableField (fill = FieldFill.INSERT_UPDATE) private Date gmtModified

3. Write handler to deal with this annotation!

@ Slf4j@Component / / Note the filling strategy for public class MyMetaObjectHandler implements MetaObjectHandler {/ / insertion in the ioc container @ Override public void insertFill (MetaObject metaObject) {this.setFieldValByName ("gmtCreate", new Date (), metaObject); this.setFieldValByName ("gmtModified", new Date (), metaObject) @ Override public void updateFill (MetaObject metaObject) {this.setFieldValByName ("gmtModified", new Date (), metaObject);}}

4. Test insertion, test update, and observation time.

Soft deletion (logical deletion)

Physical deletion: removing directly from the database

Logical deletion: it is not removed from the database, but is invalidated by a variable! Deleted = 0 = > deleted = 1

1. Add a deleted field to the data table

2. Add attributes to the entity class

/ * whether to delete, 1 has been deleted, 0 has not deleted * / @ TableLogic private Boolean deleted

3. Configuration!

# configuration logic to delete mybatis-plus.global-config.db-config.logic-delete-value=1mybatis-plus.global-config.db-config.logic-not-delete-value=0

The new version of Mybatislus does not need to be configured

@ Bean public ISqlInjector sqlInjector () {return new LogicSqlInjector ();}

4. Test the deletion! The record is still in the database, but the value has changed, and the query will not show the deleted data!

Int I = userMapper.deleteById (2L); System.out.println (I); List userList = userMapper.selectList (null); userList.forEach (System.out::println); optimistic lock

Optimistic lock: the name is very optimistic, it always thinks that there will be no problem, no matter what you do, don't lock it! If there is a problem, update the value test again

Pessimistic lock: the name Siyi is very pessimistic, it always thinks that there is always something wrong, no matter what it does, it will be locked! Do it again!

Here we mainly explain the optimistic locking mechanism!

Optimistic lock implementation:

Get the current version when you check out the record

When updating, take this version with you

When performing an update, set version = newVersion where version = oldVersion

If the version is wrong, the update fails.

Optimistic lock: 1. Query first and get the version number version = 1Mui-Aupdate user set name = "tom", version = version + 1where id = 2 and version = 1Mel-B thread to finish first, at this time version = 2, it will cause A modification failure! Update user set name = "jack", version = version + 1where id = 2 and version = 1

Using the optimistic Lock plug-in in MyBatisPlus

1. Add a version field to the data. The default value of the integer is 1.

2. Add corresponding fields to the entity class

@ Version / / optimistic lock Version comment private Integer version

3. Register the component

/ / register the optimistic lock plug-in @ Bean public OptimisticLockerInterceptor optimisticLockerInterceptor () {return new OptimisticLockerInterceptor ();}

4. Test

/ / Test optimistic lock successfully! @ Testpublic void testOptimisticLocker () {/ / 1, query user information User user = userMapper.selectById (1L); / / 2, modify user information user.setName ("Simon"); / / 3, perform update operation userMapper.updateById (user);}

You can see the sql on which the update is performed

After reading this article, I believe you have a certain understanding of "how to achieve automatic update, soft deletion and optimistic lock operation in MyBatisPlus". If you want to know more about it, welcome to follow the industry information channel. Thank you for your reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report