【问题标题】:How to tell MapStruct "not" to use the Lombok Builder?如何告诉 MapStruct“不”使用 Lombok Builder?
【发布时间】:2021-07-13 19:42:25
【问题描述】:

我有以下类和映射器来映射它们。 如何将 Mapstruct 配置为“不”使用 Lombok 构建器? (不删除@Builder 注释)? 在使用最新版本的 Lombok 和 mapstruct 时,mapstruct 在使用 @Builder 注解时会自动使用 Builder。我找不到禁用它的方法,因为我需要 @AfterMapping 方法中的实例,因为构建器没有公开所有必需的方法(此用例中不允许使用 @SuperBuilder)

@Entity(name = "user_details")
@Data
@Builder
public class User extends AuditableEntityBase {

    @Version
    @NotNull
    private Integer version;

    @NotNull
    private String name;

    @NotNull
    private String email;

    @NotNull
    private Address address; // Just another Class containing another class that is mapped as well.

}

@Value
@Builder
public class UserDto extends AuditableEntityBaseDto {

    @NotNull
    private Integer version;

    @NotNull
    private String name;

    @NotNull
    private String email;


    @NotNull
    private AddressDto address;
}


@Mapper(componentModel = "spring")
class UserRestMapper {
    public abstract UserDto map(User obj);

}

    @AfterMapping
    public void decorate(User source, @MappingTarget AuditableEntityBase target) {
// Method is never called.
// Method is called in case  the second argument is: "@MappingTarget UserDto.UserDtoBuilder target"
    }

【问题讨论】:

    标签: java mapstruct


    【解决方案1】:

    如果您想禁用使用构建器,可以通过将@Builder(disableBuilder = true) 添加到您的@Mapper 来实现。

    例如

    @Mapper(componentModel = "spring", builder = @Builder(disableBuilder = true))
    class UserRestMapper {
        public abstract UserDto map(User obj);
    
    }
    

    注意@Builder来自org.mapstruct

    【讨论】:

    • 谢谢,这正是我想要的 :-) .. 愚蠢的是我没有注意到 annotatie 属性。
    • 是否也可以根据映射方法禁用它?
    【解决方案2】:

    不知道要禁用它,但为什么不这样做呢?

    @Mapper(componentModel = "spring")
    abstract class UserRestMapper {
        public abstract UserDto map(User obj);
        
        public UserDto decoratedMap(User obj) {
            UserDto mapped = map(obj);
            // your after mapping logic
            return mapped;
        }
    }
    

    【讨论】:

    • 限制太多了。抱歉,我遗漏了 User 中需要调用相同 @AfterMapping 方法的嵌套对象...我已经更改了我的最小用例(它有点太小了)
    猜你喜欢
    • 2021-05-03
    • 1970-01-01
    • 2020-12-29
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 2016-04-10
    相关资源
    最近更新 更多