When using MyBatis-Plus for conditional updates, you can useupdate
Combination of methodsWrapper
To specify the update conditions and the fields to be updated. Here is a simple example showing how to update only one field based on the criteria.
Suppose you have a name calledUser
entity class, and you only want to update the user'semail
field, leaving other fields unchanged.
import ; import ; import ; import ; @Service public class UserService { @Autowired private UserMapper userMapper; public boolean updateEmailById(Long id, String newEmail) { // Create an UpdateWrapper to build update statements UpdateWrapper<User> updateWrapper = Wrappers.<User>update() .set("email", newEmail) // Set the fields to be updated and their new values .eq("id", id); // Add a condition, here it means update according to ID // Perform the update operation and return whether it is successful return (null, updateWrapper) > 0; } }
In this example:
-
set("email", newEmail)
Specified that the field we want to update isemail
and its new value. -
eq("id", id)
Indicates that our update conditions are based onid
Fields equal to the givenid
Value. -
(null, updateWrapper)
The first parameter in can be passed intoUser
Entity object, but because we are already inUpdateWrapper
All required information is specified in , so it is passed in herenull
。
Please make sure yoursUserMapper
The interface is inherited fromBaseMapper<User>
Or a similar CRUD method was implemented.
Also, please note that this example uses a field name in the form of a string."email"
and"id"
, If your project has field policies (such as camel naming conversion), then you need to make sure that these strings match the actual column names in the database. If you are using the latest version of MyBatis-Plus, it is recommended to use field references of the entity class directly, such asUser::getEmail
andUser::getId
to avoid potential errors caused by hard-coded strings.
This is the end of this article about mybatisplus only updating one field according to conditions. For more related mybatisplus To update a field content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!