英文:
Mapstruct between objects having exactly same fields
问题
我一直在使用 mapstruct 来映射稍有不同的类的对象。
现在,我有一个用例,其中这两个类 完全 相同。
其中一个类是 BO(资格),另一个是 DTO(QualificationRecord),两者具有完全相同的字段。
如何使用 @Mapper
在这两种类型之间进行转换?
到目前为止,我正在做以下操作:
@Mapping(source = "qualificationId", target = "qualificationId")
QualificationRecord getQualificationRecordFromQualification(final Qualification qualification);
它能够生成映射器,设置所有字段。
但是,source = "qualificationId", target = "qualificationId"
似乎是多余的,我之所以不得不添加它,是因为没有无参数的 @Mapping()
注解可用。
是否有一种方法可以让映射器复制所有字段,而不需要编写多余的一行代码?
英文:
I have been using mapstruct to Map objects of classes which vary slightly.
Now, I have a usecase where the two classes are exactly same.
One of the classes is a BO (Qualification) and the other is a DTO (QualificationRecord) having exactly same fields.
How can I use a @Mapper
to convert between these two types?
So far, I am doing
@Mapping(source = "qualificationId", target = "qualificationId")
QualificationRecord getQualificationRecordFromQualification(final Qualification qualification);
And it is able to generate the mapper, setting all the fields.
But, source = "qualificationId", target = "qualificationId"
seems redundant and I had to add it only because there was no parameter-less @Mapping()
annotation available.
Is there a way to tell the Mapper to copy all the fields, without writing one redundant line?
答案1
得分: 4
只需在接口中定义映射方法,就像这样将一个对象的所有字段复制到另一个对象中:
/**
* 映射器。由MapStruct自动实现。
*/
@Mapper
public interface SomeObjMapper {
/**
* 实例。
*/
final SomeObjMapper INSTANCE = Mappers.getMapper(SomeObjMapper.class);
/**
* 映射器方法,用于将实体映射到域。由MapStruct自动实现。
*
* @param entity
* 给定的实体。
* @return 返回域对象。
*/
SomeObj entityToDomain(SomeObjEntity entity);
/**
* 映射器方法,用于将域对象映射到实体。由MapStruct自动实现。
*
* @param domain
* 给定的域对象。
* @return 返回实体。
*/
SomeObjEntity domainToEntity(SomeObj domain);
}
英文:
Just define mapping methods in an interface like this will copy all fields from one object to the other:
/**
* 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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论