Ain*_*100 2 java mapping spring spring-boot mapstruct
我看到2018年有一个类似的问题: Mapstruct to update value without overwriting,但没有解决这个问题的例子。
因此,我不知道如何解决它。
我正在使用Lombok和MapStruct
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
Run Code Online (Sandbox Code Playgroud)
UserDTO用作theUserEntity和the之间的中间体UserRequestModel(稍后会提到)。
@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
Run Code Online (Sandbox Code Playgroud)
UserRequestModel当请求到达 UserController 时使用。
@Getter
@Setter
@ToString
public class UserRequestModel {
// ------------------------------------------------------
// Attributes
// ------------------------------------------------------
private String firstName;
private String lastName;
private String email;
}// end of class
Run Code Online (Sandbox Code Playgroud)
我创建了一个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
Run Code Online (Sandbox Code Playgroud)
最后,我用来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
Run Code Online (Sandbox Code Playgroud)
上面的对象用于映射。现在,我将向您展示 和UserController的代码UserService。这个问题发生在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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
如果我尝试运行此代码,则会收到以下错误。
我使用调试器来理解这个问题,我注意到它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;
}
}
Run Code Online (Sandbox Code Playgroud)
最有可能的是,我没有做正确的事情。
您认为出现此问题是因为我没有构造函数吗?通常,如果我们不实现它,Java 会自动创建无参数构造函数。
我添加以下图像,以便我可以演示我想要做什么。也许这个流程可以有所帮助。
最有可能的是,该方法mapDtoToEntity 应该接受 2 个属性,以便将 映射UserDTO到UserEntity。例如:
userMapper.mapDtoToEntity(userDto, userEntity);
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
谢谢塞尔吉奥·莱马!!!我在我的代码中添加了您的修改,一切正常!
更新后的版本
我必须将以下方法添加到UserMapper类中。
@Mapping(target = "firstName", source = "firstName")
@Mapping(target = "lastName", source = "lastName")
@Mapping(target = "email", source = "email")
void updateFields(@MappingTarget UserEntity entity, UserDTO dto);
Run Code Online (Sandbox Code Playgroud)
然后,我必须修改类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
Run Code Online (Sandbox Code Playgroud)
事实上,UserEntity每次 PUT 完成时您都会创建一个新实例。应该做的是更新所需的字段。为此,您可以使用@MappingTarget如下:
@Mapping(target = "targetFieldName", source = "sourceFieldName")
void updateFields(@MappingTarget UserEntity entity, UserDTO dto);
Run Code Online (Sandbox Code Playgroud)
该注释确保不会创建新对象,它将维护原始对象,仅更新所需的字段。
| 归档时间: |
|
| 查看次数: |
3230 次 |
| 最近记录: |