我一直在使用mapstruct映射略有不同的类的对象。
现在,我有一个用例,其中两个类完全相同。 其中一个类是 BO(Qualification),另一个类是具有完全相同字段的 DTO(QualificationRecord)。
如何使用 @Mapper
在这两种类型之间进行转换?
到目前为止,我正在做
@Mapping(source = "qualificationId", target = "qualificationId")
QualificationRecord getQualificationRecordFromQualification(final Qualification qualification);
并且它能够生成映射器,设置所有字段。
但是,source = "qualificationId", target = "qualificationId"
似乎是多余的,我不得不添加它只是因为没有可用的无参数 @Mapping()
注释。
有没有一种方法可以告诉映射器复制所有字段,而不需要编写多余的行?
最佳答案
只需在接口(interface)中定义映射方法,如下所示,即可将所有字段从一个对象复制到另一个对象:
/**
* Mapper. Automatically implemented by mapstruct.
*
*/
@Mapper
public interface SomeObjMapper {
/**
* instance.
*/
final SomeObjMapper INSTANCE = Mappers.getMapper(SomeObjMapper.class);
/**
* Mapper method to map entity to domain. Automatically implemented by mapstruct.
*
* @param entity
* given entity.
* @return Returns the domain object.
*/
SomeObj entityToDomain(SomeObjEntity entity);
/**
* Mapper method to map domain object to entity. Automatically implemented by mapstruct.
*
* @param domain
* given domain object.
* @return Returns the entity.
*/
SomeObjEntity domainToEntity(SomeObj domain);
}
关于java - 具有完全相同字段的对象之间的映射结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63812245/