本文介绍了Mapstruct 生成的类使用来自父级而不是子级的 Lombok 构建器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类A(域类),一个类B(mongo db存储库层类)扩展了A,并且它们都具有Lombok @Builder.我需要在它们之间进行转换,并且为此使用Mapstruct时,实现转换类在生成类型B的对象时会使用A的Builder.这会由于不兼容的类型"而导致构建失败.如何解决这个问题?

I have class A (domain class), class B (mongo db repository layer class) extends A and both of them have Lombok @Builder on them. I need to convert between them and when I use Mapstruct for this, the implementation conversion class uses Builder from A when generating object of type B. This results in build failure due to "incompatible types". How to fix this?

@Builder
class A {

}

@Document
@Builder
class B extends A{
}

@Mapper
public interface ClassMapper {
   B mapToDocument(A domainObject);
}

此代码生成以下Mapstruct文件:

This code generates the following Mapstruct file:

public class ClassMapperImpl implements ClassMapper{
   @Override
   public B mapToDocument(A domainObject){
      if(domainObject == null){
         return null;
      }
      Builder builder = A.builder();
      //builder methods
      return builder.build(); //incompatible types due to builder generating A objects, not B
   }
}

推荐答案

即使没有映射器,您的代码也无法编译.Lombok抱怨B类中的@Builder返回了不兼容的类型:

your code cannot compile even without the mapper. Lombok complains that the @Builder in B class has incompatible type returned:

由于.builder()方法是静态的,因此无法使用继承机制.

because .builder() method is static, it cannot use inheritance mechanism.

另一种解决方案是在A类上使用@Getter,在B类上使用@Setter,然后让mapstruct为您完成映射.

another solution is to use @Getter on A class and @Setter on B class and let mapstruct do the mapping for you.

这篇关于Mapstruct 生成的类使用来自父级而不是子级的 Lombok 构建器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-19 12:23