SoFunction
Updated on 2025-03-04

Mybatisplus only updates one field according to the condition

When using MyBatis-Plus for conditional updates, you can useupdateCombination of methodsWrapperTo 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 calledUserentity class, and you only want to update the user'semailfield, 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 isemailand its new value.
  • eq("id", id)Indicates that our update conditions are based onidFields equal to the givenidValue.
  • (null, updateWrapper)The first parameter in  can be passed intoUserEntity object, but because we are already inUpdateWrapperAll required information is specified in  , so it is passed in herenull

Please make sure yoursUserMapperThe 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::getEmailandUser::getIdto 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!