首页 > 解决方案 > 具有完全相同字段的对象之间的 Mapstruct

问题描述

我一直在使用mapstruct来映射略有不同的类的对象。

现在,我有一个用例,其中两个类完全相同。其中一类是 BO(资格),另一类是具有完全相同字段的 DTO(资格记录)。

如何使用 a@Mapper在这两种类型之间进行转换?

到目前为止,我正在做

@Mapping(source = "qualificationId", target = "qualificationId")
QualificationRecord getQualificationRecordFromQualification(final Qualification qualification);

它能够生成映射器,设置所有字段。但是,source = "qualificationId", target = "qualificationId"这似乎是多余的,我不得不添加它只是因为没有@Mapping()可用的无参数注释。

有没有办法告诉映射器复制所有字段,而不写一个多余的行?

标签: javamapstruct

解决方案


只需在这样的接口中定义映射方法即可将所有字段从一个对象复制到另一个对象:

/**
     * 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);

}

推荐阅读