alb*_*ert 3 java mapping dto mapstruct java-ee-8
我发现了很多与此相关的主题,但在我看来,所有解决方案都走向了错误的方向。
\n\n那么...在这种情况下我该如何使用 MapStruct 映射?
\n\n抽象类人:
\n\npublic abstract class Person implements Serializable{\n\n private String name;\n private String somethingToIgnore\n\n //Getter and Setter\n\n}\nRun Code Online (Sandbox Code Playgroud)\n\n普通的映射器不能\xc2\xb4工作:
\n\n@Mapper(componentModel = 'cdi')\npublic interface PersonMapper{\n\n @Mapping(target = 'somethingToIgnore', ignore = 'true')\n Person toPerson(PersonDTO source);\n\n @InheritInverseConfiguration\n PersonDTO toPersonDtO(Person source);\n\n}\nRun Code Online (Sandbox Code Playgroud)\n\n我不允许映射抽象类。我应该使用工厂方法。我尝试过,但我根本不知道这个工厂方法应该是什么样子......
\n\n我的尝试:
\n\n@Mapper\npublic interface PersonMapper {\n\n PersonMapper INSTANCE = Mappers.getMapper( PersonMapper.class );\n\n Person toPerson(PersonDTO source);\n\n PersonDTO toPersonDtO(Person source);\n}\n\nRun Code Online (Sandbox Code Playgroud)\n\n@Mapper\npublic abstract class PersonMapper {\n\n public static final PersonMapper INSTANCE = Mappers.getMapper( PersonMapper.class );\n\n Person toPerson(PersonDTO source);\n\n PersonDTO toPersonDtO(Person source);\n}\n\nRun Code Online (Sandbox Code Playgroud)\n\n我错过了什么并且做错了什么?\n提前致谢。
\nMapStruct doesn't know how to map to abstract class, because it cannot instantiate it. I expect that you have some implementation of Person. You need to provide method which will create object of a Person like this:
@Mapper
public interface PersonMapper {
Person toPerson(PersonDTO source);
PersonDTO toPersonDtO(Person source);
default Person createPerson() {
return new PersonImpl();
}
}
Run Code Online (Sandbox Code Playgroud)
This way MapStruct will use this method to create Person instance and than map the properties like usual. You can find more about object factories in the documentation.
| 归档时间: |
|
| 查看次数: |
24169 次 |
| 最近记录: |