简体   繁体   English

使用 MapStruct 将抽象类映射到 DTO

[英]Map abstract class to DTO with MapStruct

I found a lot of topics to this but all solutions went into a wrong direction in my eyes.我找到了很多关于此的主题,但所有解决方案在我看来都朝着错误的方向发展。

So... How do i use MapStruct mapping for this case?那么......我如何在这种情况下使用 MapStruct 映射?

abstract class Person:抽象类人:

public abstract class Person implements Serializable{

     private String name;
     private String somethingToIgnore

     //Getter and Setter

}

The normal Mapper doesn´t work:普通的 Mapper 不起作用:

@Mapper(componentModel = 'cdi')
public interface PersonMapper{

    @Mapping(target = 'somethingToIgnore', ignore = 'true')
    Person toPerson(PersonDTO source);

    @InheritInverseConfiguration
    PersonDTO toPersonDtO(Person source);

}

I am not allowed to map an abstract class.我不允许映射抽象类。 I should use the a factory method.我应该使用工厂方法。 I tried but i simply have no clue how this factoy method should look like...我试过了,但我根本不知道这个工厂方法应该是什么样子......

My attempt:我的尝试:

@Mapper
public interface PersonMapper {

    PersonMapper INSTANCE = Mappers.getMapper( PersonMapper.class );

    Person toPerson(PersonDTO source);

    PersonDTO toPersonDtO(Person source);
}

@Mapper
public abstract class PersonMapper {

    public static final PersonMapper INSTANCE = Mappers.getMapper( PersonMapper.class );

    Person toPerson(PersonDTO source);

    PersonDTO toPersonDtO(Person source);
}

What am i missing and doing wrong ?我错过了什么,做错了什么? Thanks in advance.提前致谢。

MapStruct doesn't know how to map to abstract class, because it cannot instantiate it. MapStruct 不知道如何映射到抽象类,因为它无法实例化它。 I expect that you have some implementation of Person .我希望你有一些Person实现。 You need to provide method which will create object of a Person like this:您需要提供方法来创建这样的Person对象:

@Mapper
public interface PersonMapper {

    Person toPerson(PersonDTO source);

    PersonDTO toPersonDtO(Person source);

    default Person createPerson() {
        return new PersonImpl();
    }
}

This way MapStruct will use this method to create Person instance and than map the properties like usual.这样 MapStruct 将使用此方法创建Person实例,然后像往常一样映射属性。 You can find more about object factories in the documentation .您可以在文档中找到有关对象工厂的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM