In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the mybatisplus compound primary key CRUD example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
Mybatisplus compound primary key CRUD requirement description
Recently, I received an interesting request to be a data burial point for users to watch and learn the length of the video.
The API for storing the length of time for users to watch videos and record will certainly be called frequently, because every user will call it at a specified time interval. If you directly operate the database in this interface, it will put some pressure on our database. It is not allowed in my code, and this is how I complete this requirement:
First of all, the length of time and records of users watching videos are stored in Aliyun's log database, and then the data of users watching videos are pulled from Aliyun's log database by timer and synchronized to our database.
And this is the last step, synchronizing the data to the database, where the amount of data must be huge, so I made a sub-table.
But although there is a lot of data in the sub-table, if I edit the data through the self-increasing primary key id, then I have to query it from the database before updating the data, and then update it.
In the case of a large amount of data, it will still cause a lot of pressure on our database, and the execution time of this timer will be enlarged, which I cannot accept.
So directly using the compound primary key to update the data in batches with the video id+ user id will be much faster, but mybatisplus only supports a single primary key operation, which has led to an impasse in my clear thinking.
But it allowed me to find a framework that supports compound primary keys.
Mybatisplus-plus
Doesn't that look crazy? What is plus-plus? Don't worry, let's look at the code first.
Note the version compatibility between mybatisplus and mybatisplus-plus
First introduce the jar package
Com.github.jeffreyning mybatisplus-plus 1.5.1-RELEASE com.baomidou mybatis-plus-boot-starter 3.1.0 com.baomidou mybatis-plus-generator 3.1.0
PO object
Package com.youxue.model.lesson;import com.baomidou.mybatisplus.annotation.TableField;import com.baomidou.mybatisplus.annotation.TableName;import com.fasterxml.jackson.databind.annotation.JsonDeserialize;import com.fasterxml.jackson.databind.annotation.JsonSerialize;import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;import com.github.jeffreyning.mybatisplus.anno.MppMultiId;import com.youxue.sharding.annotation.TableIndex;import com.youxue.sharding.annotation.TableIndices Import com.youxue.sharding.model.BaseShardingPo;import io.swagger.annotations.ApiModel;import io.swagger.annotations.ApiModelProperty;import lombok.Data;import lombok.EqualsAndHashCode;import lombok.experimental.Accessors;import java.io.Serializable;import java.time.LocalDateTime;/** *
* length of time users watch videos * * @ author dx * @ since 2021-6-22 * / @ Data@EqualsAndHashCode (callSuper = false) @ Accessors (chain = true) @ TableName ("UserWatchVideoLog") @ ApiModel (value= "UserWatchVideoLogPo object", description= "user viewing time table") @ TableIndices ({@ TableIndex (name = "IX_USERID", ddl = "CREATE NONCLUSTERED INDEX [IX_USERID] ON UserWatchVideoLog ([UserId] DESC")) @ TableIndex (name = "IX_LESSONITEMID_USERID", ddl = "CREATE NONCLUSTERED INDEX [IX_LESSONITEMID_USERID] ON UserWatchVideoLog (LessonItemId ASC,UserId ASC)") public class UserWatchVideoLogPo implements Serializable, BaseShardingPo {@ MppMultiId / / compound primary key @ TableField ("userId") @ ApiModelProperty (value = "user id") private Integer userId @ TableField ("lessonItemId") @ ApiModelProperty (value = "sub-course id") private Integer lessonItemId; @ ApiModelProperty (value = "viewing duration in seconds") @ TableField ("seconds") private Integer seconds; @ ApiModelProperty (value = "subject id") @ TableField ("subjectId") private Integer subjectId; @ ApiModelProperty (value = "Video viewing duration in seconds") @ TableField ("VideoProgress") private Integer videoProgress @ ApiModelProperty (value = "video source default 0") @ TableField ("[Resource]") private Integer resource; @ ApiModelProperty (value = "type default 0") @ TableField ("[Type]") private Integer type @ ApiModelProperty (value = "creation time") @ TableField ("CreateTime") @ JsonFormat (pattern = "yyyy-MM-dd HH:mm:ss") @ JsonDeserialize (using = LocalDateTimeDeserializer.class) @ JsonSerialize (using = LocalDateTimeSerializer.class) private LocalDateTime createTime; @ ApiModelProperty (value = "modification time") @ TableField ("UpdateTime") private LocalDateTime updateTime;}
The @ MppMultiId annotation is declared as a compound primary key, and the table field is declared with the @ TableField primary key
Service interface
Package com.youxue.service.lesson;import com.github.jeffreyning.mybatisplus.service.IMppService;import com.youxue.model.lesson.UserWatchVideoLogPo;/** *
* users watch video recording services *
* * @ author dx * @ since 2021-06-22 * / public interface IUserWatchVideoLogService extends IMppService {}
Impl class
Package com.youxue.service.lesson.impl;import com.github.jeffreyning.mybatisplus.service.MppServiceImpl;import com.youxue.dao.lesson.UserWatchVideoLogMapper;import com.youxue.model.lesson.UserWatchVideoLogPo;import com.youxue.service.lesson.IUserWatchVideoLogService;import org.springframework.stereotype.Service;/** *
* users watch video recording service class implementation class *
* * @ author dx * @ since 2021-6-22 * / @ Servicepublic class UserWatchVideoLogServiceImpl extends MppServiceImpl implements IUserWatchVideoLogService {}
Mapper interface
Package com.youxue.dao.lesson;import com.github.jeffreyning.mybatisplus.base.MppBaseMapper;import com.youxue.model.lesson.UserWatchVideoLogPo;/** *
* Mapper API for users to watch video recording *
* * @ author dx * @ since 2021-06-22 * / public interface UserWatchVideoLogMapper extends MppBaseMapper {}
Service inherits IMppService, mapper inherits MppBaseMapper,impl inherits MppServiceImpl, and implements service
And add @ EnableMPP annotation to the startup class
Then run it directly in the test case (no sub-table is used in the test case):
@ Autowiredprivate IUserWatchVideoLogService userWatchVideoLogService;@Testpublic void testUserWatchVideo () {UserWatchVideoLogPo userWatchVideoLogPo = new UserWatchVideoLogPo () .setUserId (6202238) .setLessonItemId (56303) .setSeconds (8888) .setResource (11); boolean create = userWatchVideoLogService.save (userWatchVideoLogPo); System.out.println (create); System.out.println ("create result:" + create) System.out.println ("= create end ="); / / breakpoint 01 UserWatchVideoLogPo watchVideoLogPo = userWatchVideoLogService.selectByMultiId (userWatchVideoLogPo); System.out.println (watchVideoLogPo.toString ()); System.out.println ("= retrieve end ="); userWatchVideoLogPo.setSeconds (99999); userWatchVideoLogPo.setResource (22) / / breakpoint 03 boolean upd = userWatchVideoLogService.updateByMultiId (userWatchVideoLogPo); System.out.println ("upd result:" + upd); System.out.println ("= update end ="); / / breakpoint 03 boolean remove = userWatchVideoLogService.deleteByMultiId (userWatchVideoLogPo); System.out.println ("remove result:" + remove); System.out.println ("= remove end =") }
I have hit a breakpoint for each method output after the save method. Let's take a look at the running results.
As you can see, there is no difference between the SQL printed by the adding method and mybatisplus, and then take a look at the data in the database
It's normal. Let's take a look at the query operation.
As you can see, the where condition here is followed by two query conditions, isn't it great? Take a look at the editing operation.
The SQL that can be edited also has two conditional operations, and the data has been updated. Finally, the operation is deleted:
At this point, the CRUD supporting composite components is complete.
And the novel features of mybatisplus-plus as an upgraded version of mybatisplus certainly do not stop there.
Add, delete, modify and check according to the joint primary key of multiple fields
Native mybatisplus supports only one primary key
Mpp supports multiple fields to join primary keys (compound primary keys) to add, delete, modify and query.
Mapper needs to inherit MppBaseMapper
Fields of federated primary keys in entity classes need to be decorated with @ MppMultiId annotation
If you need to use multi-primary key related operations in service, including saveOrUpdateByMultiId and batch operations
UpdateBatchByMultiId and saveOrUpdateBatchByMultiId, which can directly inherit the IMppService interface
Optimize the paging plug-in to sort without paging
Native mybatisplus paging and sorting are bound, mpp optimizes the paging plug-in, using the MppPaginationInterceptor plug-in
Support for sorting operations without paging
The page parameter size is set to-1 to fetch all the data without paging, and OrderItem is set to sort.
Automatic filling optimization function & automatically scanning Entity class to build ResultMap function
Native mybatisplus can only be populated with% swatches 1 and now, and mybatisplus-plus populates the specified fields with custom complex sql when inserting or updating.
You need to set fill=FieldFill.INSERT fill=FieldFill.UPDATE or fill=FieldFill.INSERT_UPDATE with the native annotation @ TableField on the entity class field or custom padding will not be triggered
When mybatisplus-plus uses the @ InsertFill annotation to trigger the insert, execute the custom sql in the annotation to populate the entity class field
When mybatisplus-plus triggers an update with the @ UpdateFill annotation, execute the custom sql in the annotation to populate the entity class field
The primary key field can also be filled in automatically to solve the problem that the native mybatisplus does not support multiple primary keys.
Use the ColNameUtil.pn static method to get the column name corresponding to the read method in the entity class
Thank you for reading this article carefully. I hope the article "sample Analysis of mybatisplus compound key CRUD" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.