简体   繁体   English

如何为 Mapstruct 指定默认映射方法

[英]How to specify default mapping method for Mapstruct

I have simple object Client我有简单的 object 客户端

public class Client {
    String externalCode;
    String name;
    String surname;
}

And I want to map it to nearly identical object我想将 map 与几乎相同的 object

public class User {
    String internalCode;
    String name;
    String surname;
}

See, I want externalCode to be mapped to internalCode.看,我希望将 externalCode 映射到 internalCode。 And I have a method which does that.我有一个方法可以做到这一点。 I have marker my method with my custom @CodeMapping annotation and put that annotation to qualifiedBy parameter.我用我的自定义 @CodeMapping 注释标记了我的方法,并将该注释放入qualifiedBy 参数。 So, here is my mapper.所以,这是我的映射器。

@Mapper()
ClientMapper {
     @CodeMapping
     String toInternalCode(String externalCode) {
          return externalCode + " internal part";
     }

    @Mapping(target = "internalCode", source = "externalCode", qualifiedBy = CodeMapping.class)
    User toUser(Client client);
}

The problem is that name and surname fields are also mapped using toInternalCode method.问题是 name 和 surname 字段也使用 toInternalCode 方法映射。 Mapstruct sees that I have defined a method, which maps String to String and thinks it should be used in all cases. Mapstruct 看到我定义了一个方法,它将 String 映射到 String 并认为它应该在所有情况下都使用。

Is there a way to tell Mapstruct, that if no qualifiers are specified, direct mapping should be used?有没有办法告诉 Mapstruct,如果没有指定限定符,应该使用直接映射? Or make my own method which takes string and return it and tell Mapstruct it should use that method by default?或者制作我自己的方法,它接受字符串并返回它并告诉 Mapstruct 它应该默认使用该方法?

Most likely the toInternalCode is used by all methods because the @CodeMapping annotation is not meta annotated with @Qualifier (from org.mapstruct.Qualifier ).很可能所有方法都使用了toInternalCode ,因为@CodeMapping注释没有使用@Qualifier进行元注释(来自org.mapstruct.Qualifier )。

The @CodeMapping should be defined in the following way: @CodeMapping应按以下方式定义:

import org.mapstruct.Qualifier;

@Qualifier
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS)
public @interface CodeMapping {
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM