1. Overview
MyBatis-Plus provides a saveOrUpdate() method. By default, you can update or insert operations based on whether the primary key exists. However, in actual scenarios, we will encounter update or insert according to the specified field.
The following records how to update or insert according to the specified field.
2. Implementation method
- Function description: Make judgments based on the primary key ID of the entity object. If there is, the record will be updated, otherwise the record will be inserted.
- Return value: boolean, indicating whether the insertion or update operation is successful.
// @TableId If the annotation attribute value exists, update the record, no record is insertedboolean saveOrUpdate(T entity); // Try to update according to updateWrapper, continue to execute saveOrUpdate(T) methodboolean saveOrUpdate(T entity, Wrapper<T> updateWrapper);
To update according to the specified field, use the saveOrUpdate(T entity, Wrapper<T> updateWrapper) method.
There is a method like this in IService that receives two parameters.
default boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper) { return (entity, updateWrapper) || (entity); }
The execution logic during execution is as follows:
- First, query which record needs to be updated according to updateWrapper;
- If the record can be queried, an update operation will be performed. When updating, it will be updated according to the value of the entity object attribute. Note that the null value will be ignored. If the record cannot be queried, the entity object will be inserted;
A detailed explanation is given in a piece of code:
// Import the necessary classesimport ; import ; // Create an UpdateWrapper object and specify query conditionsUpdateWrapper<User> updateWrapper = (); ("id", 111); // Suppose here is your specified field and condition // Call saveOrUpdate method to pass in entity objects and UpdateWrapper objects(user, updateWrapper);
3. Summary
Overall,saveOrUpdate(T entity, Wrapper updateWrapper)
method
A query will be performed based on the specified conditions, and then automatically decide whether to perform an update operation or an insert operation based on the query result, thereby realizing the logic of saving or updating according to the specified fields.
The above is personal experience. I hope you can give you a reference and I hope you can support me more.