问题描述
我一直在使用mapstruct映射稍有不同的类的对象。
现在,我有一个用例,其中两个类完全相同。 一类是BO(资格),另一类是DTO(QualificationRecord),它们具有完全相同的字段。
如何使用@Mapper
在这两种类型之间进行转换?
到目前为止,我正在做
@Mapping(source = "qualificationId",target = "qualificationId")
QualificationRecord getQualificationRecordFromQualification(final Qualification qualification);
它能够生成映射器,设置所有字段。
但是,source = "qualificationId",target = "qualificationId"
似乎是多余的,我之所以必须添加它,是因为没有可用的无参数的@Mapping()
批注。
有没有一种方法可以告诉Mapper复制所有字段,而不用写多余的行?
解决方法
只需在这样的接口中定义映射方法,即可将所有字段从一个对象复制到另一个对象:
/**
* 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);
}