简体   繁体   中英

mapstruct qualifiedByName without parameters simplify expression

I would like to set a constant on the field, but with method call, i do not want to create an expression it looks terrible, i would like to simplify this call

 @Mapping(target = "channelNotification", expression= "java(new ChannelNotification[]{ " +
                "new ChannelNotification(\"email\", 10)})")

to get something like this:

 @Mapping(target = "channel", qualifiedByName = "getChannel")
    Notification convert(Email emailEntity);

 @Named("getChannel")
    default Channel[] getChannel() {//with empty params
        return new Channel[]{new Channel("email", 10)};
    }

Source entity doesn't have field channelNotification, and i don't need to use it. I just want to set a constant like constant = *, but with method call

This is currently not possible. However, what you can do is to use a combination of constant and qualifiedByName .

eg

    @Mapping(target = "channel", constant = "email" qualifiedByName = "getChannel")
    Notification convert(Email emailEntity);

    @Named("getChannel")
    default Channel[] getChannel(String channelType) {
        Channel channel;
        if ("email".equals(channelType)) {
            channel = new Channel("email", 10);
        } else {
            throw new IllegalArgumentException("unknown channel type " + channelType);
        }

        return new Channel[]{channel};
    }

What is not known that much is that constant works in a similar way with qualifiers as other Mapping#source . Since 1.4 custom mappings between String (what is in constant ) and the target type will be looked for in order to convert the constant value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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