MapStruct生成错误的映射代码,而没有任何反向配置?

问题描述 投票:0回答:1

我有一个@MapperConfig看起来像这样。

@MapperConfig(componentModel = "spring")
public interface SomeEntityTypeMapperConfig {

    @Mapping(target = PROPERTY_NAME_ENTITY)
    @Mapping(source = SomeEntity.ATTRIBUTE_NAME_ID, target = SomeEntityType.PROPERTY_NAME_ID)
    @Mapping(source = SomeEntity.PROPERTY_NAME_CREATED_AT, target = SomeEntityType.PROPERTY_NAME_CREATED_AT)
    @Mapping(source = SomeEntity.PROPERTY_NAME_UPDATED_AT, target = SomeEntityType.PROPERTY_NAME_UPDATED_AT)
    @Mapping(source = SomeEntity.PROPERTY_NAME_CREATED_BY, target = SomeEntityType.PROPERTY_NAME_CREATED_BY)
    @Mapping(source = SomeEntity.PROPERTY_NAME_UPDATED_BY, target = SomeEntityType.PROPERTY_NAME_UPDATED_BY)
    SomeEntityType<?, ?> fromEntity(SomeEntity entity);

    // No @Mapping
    void toEntity(SomeEntityType<?, ?> type, @MappingTarget SomeEntity entity);
}

这是我的基本映射器界面。

public interface SomeEntityTypeMapper<T extends SomeEntityType<?, U>, U extends SomeEntity> {

    T fromEntity(U entity);

    void toEntity(T type, @MappingTarget U entity);
}

这是我的真实映射器。

@Mapper(config = SomeEntityTypeMapperConfig.class)
public interface UserTypeMapper extends SomeEntityTypeMapper<UserType, User> {

    @Mapping(source = User.ATTRIBUTE_NAME_NAME, target = UserType.PROPERTY_NAME_NAME)
    @Override
    UserType fromEntity(User entity);

    @Mapping(source = UserType.PROPERTY_NAME_NAME, target = User.ATTRIBUTE_NAME_NAME)
    @Override
    void toEntity(UserType type, @MappingTarget User entity);
}

并且MapStruct生成以下具有不想要的映射的impl类。

public class UserTypeMapperImpl implements UserTypeMapper {

    @Override
    public UserType fromEntity(User entity) {
        if ( entity == null ) {
            return null;
        }
        UserType userType = new UserType();
        userType.setName( entity.getName() );           // explicitly configured
        userType.setId( entity.getId() );               // inherited from the config
        userType.setCreatedAt( entity.getCreatedAt() ); // inherited from the config
        userType.setUpdatedAt( entity.getUpdatedAt() ); // inherited from the config
        userType.setCreatedBy( entity.getCreatedBy() ); // inherited from the config
        userType.setUpdatedBy( entity.getUpdatedBy() ); // inherited from the config
        return userType;
    }

    @Override
    public void toEntity(UserType type, User entity) {
        if ( type == null ) {
            return;
        }
        entity.setName( type.getName() );           // explicitly configured
        entity.setCreatedAt( type.getCreatedAt() ); // UNWANTED!!!
        entity.setUpdatedAt( type.getUpdatedAt() ); // UNWANTED!!!
        entity.setUpdatedBy( type.getUpdatedBy() ); // UNWANTED!!!
        entity.setId( type.getId() );               // UNWANTED!!!
        entity.setCreatedBy( type.getCreatedBy() ); // UNWANTED!!!
    }
}

我做错了什么以及如何解决?

mapstruct
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.