Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update an existing bean instance with mapstruct and keep some old fields

Tags:

mapstruct

I want to update an existing bean like asked here.

Using @Mapping( target = "id", ignore = true ) to keep the old id and only update all the other fields does not work though. The id is still updated. This also applies to using @BeanMapping(ignoreByDefault = true) and trying to map each field manually.

My mapping:

@Mapping(target = "id", ignore = true)
void updateUsersFromDto(List<UserDto> dtos, @MappingTarget List<User> entities);
like image 500
Johannes Pertl Avatar asked Aug 15 '26 22:08

Johannes Pertl


1 Answers

1 - declare a single object mapping method (updateUserFromUserDto)
2 - declare the list of object mapping method that will use the updateUserFromUserDto to update each element of the list (updateUsersFromUsersDto)

This should work:

@Mapper(componentModel = "spring")
public interface UserMapper {
 
    UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);
    
    @Named("updateUserFromUserDto")
    @Mapping(target = "id", ignore = true)
    void updateUserFromUserDto(UserDto dto, @MappingTarget User entity);
    
    // I'm not sure if @MappingTarget is required or not here, since it is already present in updateUserFromUserDto
    @IterableMapping(qualifiedByName = "updateUserFromUserDto")
    void updateUsersFromUsersDto(List<UserDto> dtos, @MappingTarget List<User> entities);
    
}
like image 134
Paul Marcelin Bejan Avatar answered Aug 21 '26 03:08

Paul Marcelin Bejan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!