Is it possible to achieve the same effect as @MappingTarget without using a Setter in MapStruct?

Viewed 60

I understand that @MappingTarget must be accompanied by a @Setter.

However, for safety reasons I don't want to use @Setter for Entity.

Assuming that the fields of the Update Entity and the fields of the DTO are the same, is there a way to achieve the same effect as using @MappingTarget without using @Setter?

@Entity(name = "ad_config")
public class AdConfigEntity extends BaseEntity {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private int adBannerId;
   private String adBannerTitle;
   private String adType;
   private String adCategory;
}

and

@AllArgsConstructor
@Getter
public static class UpdateDto {
    private String adType;
    private String adCategory;
}

and Don't have mapper (I don't know way)

void updateEntity(AdConfigDto.UpdateDto updateDto, @MappingTarget AdConfigEntity adConfig);

I get the same effect as this code. But it's not usable.

I don't want to use setters on entities.

1 Answers

If you have only one constructor, it will be used automatically if not, you can add @Default annotation to the constructor you want to use (i suppose the AllArgsConstructor).

Note: When using a constructor then the names of the parameters of the constructor will be used and matched to the target properties.

Then you can create your own annotation to ignore the target properties (in this way, the MapStruct will not use the setter to set the properties) :

@Retention(RetentionPolicy.CLASS)
@Mapping(target = "property1", ignore = true)
@Mapping(target = "property2", ignore = true)
public @interface DefaultIgnoreMappings { }

and use it on the mapper method.

@DefaultIgnoreMappings
TargetObject map(SourceObject sourceObject)

More info:

Related