有没有一种方法可以防止MapStruct在记录更新期间覆盖值?

时间:2020-11-01 10:45:19

标签: java spring spring-boot mapping mapstruct

我看到2018年有一个类似的问题: Mapstruct to update values without overwriting,但没有解决此问题的示例。

因此,我不知道如何解决。

我正在使用LombokMapStruct

UserEntity代表数据库中的表

@Getter
@Setter
@Entity
@Table(name = "users")
public class UserEntity implements Serializable {

    private static final long serialVersionUID = -3549451006888843499L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)     // this specifies that the id will be auto-incremented by the database
    private Long id;
    
    @Column( nullable = false)
    private String userId;
    
    @Column( nullable = false, length = 50)
    private String firstName;
    
    @Column( nullable = false, length = 50)
    private String lastName;
    
    @Column( nullable = false, length = 120)
    private String email;
    
    @Column( nullable = false)
    private String encryptedPassword;   // I am encrypting the password during first insertion of a new record

}// end of class

UserDTO用作UserEntityUserRequestModel之间的中介(我将在后面提到)。

@Getter
@Setter
@ToString
public class UserDTO implements Serializable {

    private static final long serialVersionUID = -2583091281719120521L;
    
//  ------------------------------------------------------
//  Attributes
//  ------------------------------------------------------
    private Long id;            // actual id from the database table
    private String userId;      // public user id
    private String firstName;
    private String lastName;
    private String email;
    private String password;
    private String encryptedPassword;       // in the database we store the encrypted password  

}// end of class

UserRequestModel在请求到达UserController时使用。

@Getter
@Setter
@ToString
public class UserRequestModel {
    
//  ------------------------------------------------------
//  Attributes
//  ------------------------------------------------------
    private String firstName;
    private String lastName;
    private String email;
    
}// end of class

我创建了一个UserMapper使用的MapStruct接口。

@Mapper(componentModel = "spring", nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
public interface UserMapper {

    @Mapping(target = "password", ignore = true)
    UserDTO mapEntityToDto(UserEntity userEntity);

    @Mapping(target = "encryptedPassword")
    UserEntity mapDtoToEntity(UserDTO userDto);
    
    UserResponseModel mapDtoToResponseModel(UserDTO userDto);
    
    @Mapping(target = "encryptedPassword", ignore = true)
    @Mapping(target = "id", ignore = true)
    @Mapping(target = "userId", ignore = true)
    UserDTO mapUserRequestModelToDto(UserRequestModel userRequestModel);
    
}// end of interface

最后,我使用UserResponseModel将记录返回到客户端应用程序。

@Getter
@Setter
@ToString
public class UserResponseModel {
    
//  ------------------------------------------------------
//  Attributes
//  ------------------------------------------------------
    
    // This is NOT the actual usedId in the database!!!
    // We should not provide the actual value. For security reasons.
    // Think of it as a public user id.
    private String userId;
    private String firstName;
    private String lastName;
    private String email;

}// end of class

上面的对象用于映射。现在,我将向您展示UserControllerUserService中的代码。此问题发生在UserService类内部。

@PutMapping(path = "/{id}")
public UserResponseModel updateUser(@PathVariable("id") String id , @RequestBody UserRequestModel userRequestModel) {
        
    UserResponseModel returnValue = new UserResponseModel();
        
    UserDTO userDTO = userMapper.mapUserRequestModelToDto(userRequestModel);
        
    // call the method to update the user and return the updated object as a UserDTO
    UserDTO updatedUser = userService.updateUser(id, userDTO);
        
    returnValue = userMapper.mapDtoToResponseModel(updatedUser);
        
    return returnValue;
        
}// end of updateUser

UserService用于实现应用程序的业务逻辑。

@Override
public UserDTO updateUser(String userId, UserDTO user) {
        
    UserDTO returnValue = new UserDTO();
        
    UserEntity userEntity = userRepository.findByUserId(userId);
        
    if(userEntity == null) {
        throw new UserServiceException("No record found with the specific id!");        // our own exception
    }
        
    // get the changes from the DTO and map them to the Entity
    // this did not work. The values of the Entity were set to null if they were not assigned in the DTO
    userEntity = userMapper.mapDtoToEntity(user);
        
    // If I set the values of the Entity manually, then it works
//      userEntity.setFirstName(user.getFirstName());
//      userEntity.setLastName(user.getLastName());
//      userEntity.setEmail(user.getEmail());
        
    // save the Entity
    userRepository.save(userEntity);
        
    returnValue = userMapper.mapEntityToDto(userEntity);
        
    return returnValue;
        
}// end of updateUser

如果我尝试运行此代码,则会出现以下错误。

enter image description here

我使用调试器来了解此问题,并且我注意到MapStruct会覆盖所有属性,而不仅仅是覆盖请求中已发送的那些属性。

MapStruct自动生成的代码如下:

@Generated(
    value = "org.mapstruct.ap.MappingProcessor",
    date = "2020-11-01T11:56:36+0200",
    comments = "version: 1.4.1.Final, compiler: Eclipse JDT (IDE) 3.21.0.v20200304-1404, environment: Java 11.0.9 (Ubuntu)"
)
@Component
public class UserMapperImpl implements UserMapper {

    @Override
    public UserDTO mapEntityToDto(UserEntity userEntity) {
        if ( userEntity == null ) {
            return null;
        }

        UserDTO userDTO = new UserDTO();

        userDTO.setEmail( userEntity.getEmail() );
        userDTO.setEncryptedPassword( userEntity.getEncryptedPassword() );
        userDTO.setFirstName( userEntity.getFirstName() );
        userDTO.setId( userEntity.getId() );
        userDTO.setLastName( userEntity.getLastName() );
        userDTO.setUserId( userEntity.getUserId() );

        return userDTO;
    }

    @Override
    public UserEntity mapDtoToEntity(UserDTO userDto) {
        if ( userDto == null ) {
            return null;
        }

        UserEntity userEntity = new UserEntity();

        userEntity.setEncryptedPassword( userDto.getEncryptedPassword() );
        userEntity.setEmail( userDto.getEmail() );
        userEntity.setFirstName( userDto.getFirstName() );
        userEntity.setId( userDto.getId() );
        userEntity.setLastName( userDto.getLastName() );
        userEntity.setUserId( userDto.getUserId() );

        return userEntity;
    }

    @Override
    public UserResponseModel mapDtoToResponseModel(UserDTO userDto) {
        if ( userDto == null ) {
            return null;
        }

        UserResponseModel userResponseModel = new UserResponseModel();

        userResponseModel.setEmail( userDto.getEmail() );
        userResponseModel.setFirstName( userDto.getFirstName() );
        userResponseModel.setLastName( userDto.getLastName() );
        userResponseModel.setUserId( userDto.getUserId() );

        return userResponseModel;
    }

    @Override
    public UserDTO mapUserRequestModelToDto(UserRequestModel userRequestModel) {
        if ( userRequestModel == null ) {
            return null;
        }

        UserDTO userDTO = new UserDTO();

        userDTO.setEmail( userRequestModel.getEmail() );
        userDTO.setFirstName( userRequestModel.getFirstName() );
        userDTO.setLastName( userRequestModel.getLastName() );
        userDTO.setPassword( userRequestModel.getPassword() );

        return userDTO;
    }
}

很可能是我做的不正确。

您是否认为此问题是由于我没有构造函数而发生的?如果没有实现,通常Java会自动创建无参数的构造函数。

我正在添加以下图像,以便可以演示我想做的事情。也许这个流程会有所帮助。

enter image description here

很可能方法mapDtoToEntity 应接受2个属性,以便将UserDTO映射到UserEntity。例如:

userMapper.mapDtoToEntity(userDto, userEntity);
public UserEntity mapDtoToEntity(UserDTO userDto, UserEntity userEntity) {
        
    if( userDto == null ) {
        return null;
    }
        
    // set ONLY the attributes of the UserEntity that were assigned 
    // to the UserDTO by the UserRequestModel. In the current case only 3 attributes
        
    
    // return the updated UserEntity
        
}

谢谢Sergio Lema !!!我在代码中添加了您的修改,一切正常!

更新版本

我必须将以下方法添加到UserMapper类中。

@Mapping(target = "firstName", source = "firstName")
@Mapping(target = "lastName", source = "lastName")
@Mapping(target = "email", source = "email")
void updateFields(@MappingTarget UserEntity entity, UserDTO dto);

然后,我不得不在updateUser类中修改UserService方法。

@Override
public UserDTO updateUser(String userId, UserDTO user) {
        
    UserDTO returnValue = new UserDTO();

    UserEntity userEntity = userRepository.findByUserId(userId);

    if (userEntity == null)
            throw new UserServiceException(ErrorMessages.NO_RECORD_FOUND.getErrorMessage());
        
    // update only specific fields of userEntity
    userMapper.updateFields( userEntity, user);

    userRepository.save(userEntity);
        
    // map again UserEntity to UserDTO in order to send it back
    returnValue = userMapper.mapEntityToDto(userEntity);

    return returnValue;
        
}// end of updateUser

1 个答案:

答案 0 :(得分:2)

实际上,每次执行PUT时,您都在创建UserEntity的新实例。应该做的是对所需字段的更新。为此,您可以按以下方式使用@MappingTarget

@Mapping(target = "targetFieldName", source = "sourceFieldName")
void updateFields(@MappingTarget UserEntity entity, UserDTO dto);

此注释可确保不创建任何新对象,它会维护原始对象,只是更新所需的字段。