Mapstruct 生成的类使用来自父级而不是子级的 Lombok 构建器

编程入门 行业动态 更新时间:2024-10-10 09:26:06
本文介绍了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:

返回类型与A.builder()不兼容

The return type is incompatible with A.builder()

由于.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 构建器

本文发布于:2023-11-23 04:21:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1620068.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而不是   Mapstruct   Lombok

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!