1

background

The project uses mapstruct to copy the object attributes. Multiple entity classes of the project have the same attributes, such as createTime . When configuring the mapping, if you ignore a certain mapping data, or Modify the mapping attribute name, then each @Mappings must be configured:

 @Mappings(value = {
        @Mapping(target = "id", ignore = true),
        @Mapping(source = "createTime", target = "insertTime")
})

Is it possible to extract the same configuration like this?

solution

Official documentation: MapStruct 1.4.2.Final Reference Guide
image.png

code

public configuration:

 @Retention(RetentionPolicy.CLASS)
@Mappings(value = {
        @Mapping(target = "id", ignore = true),
        @Mapping(source = "createTime", target = "insertTime")
})
public @interface CommonEntityMapping {

}

actual use:

 @Mappings(value = {
        @Mapping(source = "filed1", target = "field2")
})
@CommonEntityMapping
MyEntity convert(MyModel myModel);

另:项目刚mapstruct版本是1.2.0-Final ,不支持@Mappings ,升级到1.4.2-Final Later supported.

Advanced

What if you only want a class with many fields, but only want to map a few fields that are missing?
Can be set at @Mapping ignore = true :

 @Mapping(target = "id", ignore = true)

But as the appeal said, if the class has many fields, it is too troublesome to add configuration to each field. Is there any other way?
Fields that are not configured @Mapping can be ignored by configuring the @BeanMapping(ignoreByDefault = true) class. MapStruct 1.4.2.Final Reference Guide - defining-mapper
You can also configure unmappedTargetPolicy . MapStruct 1.4.2.Final Reference Guide - shared-configurations


noname
314 声望49 粉丝

一只菜狗