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

Mybatis-Plus advanced paging, optimistic lock plug-in, general enumeration and multi-data source instance analysis

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces Mybatis-Plus advanced paging, optimistic lock plug-in, general enumeration and multi-data source instance analysis related knowledge, detailed and easy to understand, simple and fast operation, has a certain reference value, I believe that after reading this Mybatis-Plus advanced paging, optimistic lock plug-in, general enumeration and multi-data source instance analysis article will have a harvest, let's take a look at it.

Paging plug-in

The paging plug-in is included in    MP, and you only need to make a simple configuration in the configuration class to use the paging related features. The paging plug-in is often related to the front-end paging display function. In order to beautifully display the queried data at the front end, the paging plug-in is usually used to divide all the data into many pages for display, and the switch between different pages uses buttons to complete the plug-in configuration class of MP.

@ Configurationpublic class MybatisPlusConfiguration {@ Bean public MybatisPlusInterceptor mybatisPlusInterceptor () {/ / create a MybatisPlus plug-in interceptor MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor (); / / create a paged plug-in object and set the database type PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor (DbType.MYSQL) / / set the operation after the requested page is larger than the maximum page, true is called back to the home page, and false continues to request the default false paginationInnerInterceptor.setOverflow (true); / / set the maximum number of pages per page, default 500L,-1 unlimited paginationInnerInterceptor.setMaxLimit (500L); / / add this paging plug-in to the interceptor and return interceptor.addInnerInterceptor (paginationInnerInterceptor); return interceptor }}

Customize the method and call the paging mapper definition method

@ Mapper@Repositorypublic interface UserMapper extends BaseMapper {/ * query user information by age and return paging * @ param page pass in a page object * @ param age age * @ return return a page object * / Page selectPageVo (@ Param ("page") Page page, @ Param ("age") Integer age);}

Mapping file to write SQL statement

Select id,name,age,email from user where age > # {age}

Test method calls custom method

@ AutowiredUserMapper mapper;@Testpublic void testpage () {/ / create a page object, set the current page as page 1, each page contains 3 records Page page = new Page (2,3); / / mapper calls the selectPage method and returns the result to the above page object / / the second parameter null is to query all records, and pass a wrapper object mapper.selectPageVo if there are query conditions (page, 20) / / data of the current page System.out.println (page.getRecords ()); / / which page is the current page System.out.println (page.getCurrent ()); / / Total number of pages System.out.println (page.getPages ()); / / number of records per page System.out.println (page.getSize ()); / / Total number of records System.out.println (page.getTotal ()) / / whether there is a next page of System.out.println (page.hasNext ()); / / whether there is a previous page of System.out.println (page.hasPrevious ());} optimistic lock plug-in

To use the optimistic lock plug-in for   , you first need to know what optimistic locks are and why they appear. In real life, there is often more than one administrator in a management system. Take modifying commodity prices as an example. If there are two administrators, Xiao Li and Xiao Wang, whose original price is 100, the boss first asks Xiao Li to raise the price of the commodity by 50%. After a period of time, Xiao Wang lowered the price of the commodity by 20%. Due to Xiao Li's delay, the two people logged on to the management system to obtain the price of the commodity to modify it respectively. If Xiao Li finishes the operation, the final price will be 150 yuan, and if Wang finishes the operation, the final price will be 80 yuan, so the final price will not be 130 yuan that the boss wants. If you want to use code to implement the above case, it is more real to use threads (you can simulate the uncertainty that two people deal with successively), but in order to simplify the operation, it is Xiao Wang who finishes the operation, that is to say, the price of the final product is 80.

@ Testpublic void happyLockTest () {/ / Xiao Li inquires the price of goods Product productLi = mapper.selectById (1); / / Xiao Wang queries the prices of goods Product productWang = mapper.selectById (1); / / + 50 productLi.setPrice (productLi.getPrice () + 50); mapper.updateById (productLi); / /-20 productWang.setPrice (productWang.getPrice ()-20); mapper.updateById (productWang) / / query the final commodity price System.out.println ("final price is:" + mapper.selectById (1) .getPrice ());}

/ / console final print-> final price: 80

If there is a problem in   , there is a way to solve the problem. The reason for this problem is that two administrators get the product information and modify it at the same time. If you can use locks to limit that only one administrator can modify the data at a time, you can avoid this problem. This is pessimistic locking.

   is wrong, ah, I thought we were talking about optimistic locks. Why are we talking about pessimistic locks? Pessimistic locks lock the entire table, preventing others from modifying the table, which does a lot of damage to efficiency. So optimistic lock arises at the historic moment, optimistic lock allows anyone to modify the data in the table at any time, but a field should be added to the data table to represent the current version number of the data, and the data will be increased by one every time the data is updated. Every time the data is updated, it will be updated with the version number field as a condition for update. In this way, the previous problems can be avoided. The version obtained by both people at the same time is 0. After Xiao Li modifies it, he will add one to the value of the version field, that is, 1. When Xiao Wang modifies, he cannot find the data with version number 0 in the table and cannot modify it.

   will avoid modification conflicts, but still can not get the desired results, so you can judge the modification results of the two people. If the result of the update operation is not 0, the update is successful, otherwise you will get the information in the data table again (this time to get the latest version number) and update the operation again.

   uses the optimistic lock plug-in in MP. First, you need to add the optimistic lock plug-in to the interceptor in the configuration class, then use the @ Version flag on the version number field in the entity class, and then operate the database as usual. When performing the update operation, you will automatically splice the version number of the current query into the SQL statement as a condition.

/ add optimistic lock plug-in to interceptor interceptor.addInnerInterceptor (new OptimisticLockerInnerInterceptor ()); / / entity class label version number @ Versionprivate Integer version;// test method, test the final modification result of two people @ Testpublic void happyLockTest () {/ / Xiao Li inquires the price of goods Product productLi = mapper.selectById (1); / / Xiao Wang queries the price of goods Product productWang = mapper.selectById (1) / / + 50 int result = 0; do {/ / update failed, re-query and modify productLi = mapper.selectById (1); productLi.setPrice (productLi.getPrice () + 50); result = mapper.updateById (productLi);} while (result = = 0); / /-20 do {/ / update failed, re-query and modify productWang = mapper.selectById (1) ProductWang.setPrice (productWang.getPrice ()-20); result = mapper.updateById (productWang);} while (result = = 0); / / query the final commodity price System.out.println ("final price:" + mapper.selectById (1). GetPrice ());}

/ / console final print-> final price: 130

Universal enumeration class

   for some fields with fixed values in the table, you can use the enumeration class to store relatively simple numbers or characters in the database table, and then correspond to the specific string representation of this simple number or character, such as gender 0 for female 1 for male. This will reduce the storage pressure of the database and improve the user experience. To use MP's generic enumeration, you must first create an enumeration class, provide the getter method and full parameter constructor of the property, and use the @ EnumValue annotation to store the identified property value in the database

@ Getter@AllArgsConstructorpublic enum SexEnum {FEMALE (0, "female"), MALE (1, "male"); / / store the attribute values identified by the annotation in the database @ EnumValue private Integer sex; private String sexName;}

   then modifies the type of the attribute corresponding to the field to the enumerated type in the entity class, and then overrides the toString method to facilitate the query result to be displayed as a specific string representation of numbers or characters in the data table

/ / modify the type of the property corresponding to the field to be enumerated type private SexEnum sex / / override the toString method @ Overridepublic String toString () {return "User {" + "id=" + id + ", name='" + name +'\'+ ", sex=" + sex.getSexName () + ", age=" + age + ", email='" + email +'\'+ ", isDeleted=" + isDeleted +'}';}

Finally,    sets the package of the universal enumeration in the configuration file, which is equivalent to making the enumeration class you write take effect.

Mybatis-plus: # sets the package type-enums-package: com.xiaochen.enums of the general enumeration

test

@ Testpublic void enumTest () {User user = new User (); user.setName ("Zhang San"); user.setAge (23); user.setSex (SexEnum.FEMALE); mapper.insert (user); User user1 = mapper.selectById (6); System.out.println (user1);}

Test result

Multiple data sources

   multi-data source is to configure multiple databases as data sources in one program at the same time, which is suitable for a variety of scenarios: pure multi-database, read-write separation, one master and multi-slave, mixed mode and so on. At present, we will simulate a scenario of pure multi-database, configure two tables of two databases, and obtain the data of two tables through a test case. If we get it, the simulation of multi-database is successful.

Step 1: import dependencies

Com.baomidou mybatis-plus-boot-starter 3.5.1

Step 2: profile configuration multiple data sources

Spring:

# configure data source information

Datasource:

Dynamic:

# set the default data source or data source group. Use the default data source when none of the set data sources can be found. The default value is master.

Primary: master

# strictly matches the data source. If the default false.true does not match the specified data source, an exception is thrown. If the false does not match the specified data source, the default data source is used.

Strict: false

Datasource:

# Master data source

Master:

Driver-class-name: com.mysql.jdbc.Driver

Url: jdbc:mysql://localhost:3306/mybatis_plus

Username: root

Password: 123456

# from the data source

Slave_1:

Driver-class-name: com.mysql.jdbc.Driver

Url: jdbc:mysql://localhost:3306/test

Username: root

Password: 123456

Step 3: use the method test to query two tables in two databases as usual. the only difference is to use the @ DS annotation on the service implementation class to mark that all methods of the service implementation class operate on the specified data source.

Test classes and results

This is the end of the article on "Mybatis-Plus advanced paging, optimistic locking plug-ins, general enumeration and multi-data source instance analysis". Thank you for reading! I believe you all have some knowledge of "Mybatis-Plus advanced paging, optimistic lock plug-in, general enumeration and multi-source instance analysis". If you want to learn more, please follow the industry information channel.

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

Development

Wechat

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

12
Report