如何在将构造函数实例化与 mapstruct 和不可变的 kotlin 对象一起使用时进行部分更新

How to make a partial update while using constructor instantiation with mapstruct and immutable kotlin objects

如何在使用构造函数实例化时进行部分更新?假设我有一个 User 实体和 UserDto 对象,并且只想更新“name”而不是“login”和“passHash”。我不想让它们可变,所以我不能使用@MappingTarget。

理想情况下,我想设置“nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE”,传递一个源对象 A:用户,一个现有的(未更新的)对象 B:UserDto,映射器将返回一个对象 C:UserDto 这将是使用 A 的非空属性更新的 B 对象。

类似这样的东西 (kotlin):

@Mapper(componentModel = "spring")
interface UserMapper {
    @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
    fun createEntityFromDto(dto: UserDto, @MappingExample entity: User) : User
}

MapStruct 进行部分更新的方式是使用 @MappingTarget,这意味着您尝试更新的对象必须是可变的。没有其他方法可以执行更新。

你可以做的是使用某种构建器并使用 @MappingTarget 中的 bulder 来执行更新。

例如在 Java

@Mapper(componentModel = "spring")
public interface UserMapper {

    @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
    void updateUser(@MappingTarget User.Builder userBuilder, UserDto userDto);
}

然后您可以通过以下方式调用它

User.Builder userBuilder = entity.toBulder();
userMapper.updateUser(userBuilder, userDto);