MapStruct: How to pass input object to expression?

烂漫一生 提交于 2021-01-27 16:37:37

问题


In MapStruct version 1.1.0.Final, this was possible....

@Mappings({
    @Mapping(target = "transaction.process.details", expression = "java(MappingHelper.mapDetails(request))"),
     //more mappings
})
Response requestToResponse(Request request);

It was possible, since the mapDetails method was (by coincidence?) generated into the requestToResponse method. That's why request was not null.

Now, since 1.1.0.Final didn't work with Lombok, I had to upgrade to 1.2.0.CR2. With this version, the mapDetails will be generated into a separate method where request is not passed, so request is null within this method now and I get a NPE with the expression. (It's a sub-sub-method of requestToResponse now.)

Did I misuse the expression, so did it just work by coincidence, or does the new version has a bug? If no bug, how do I have to pass the request instance to the expression properly?


回答1:


You were / are misusing the expression. What you need to do is to map your target to your source parameter.

@Mapper(uses = { MappingHelper.class })
public interface MyMapper {

    @Mappings({
        @Mapping(target = "transaction.process.details", source = "request"),
         //more mappings
    })
    Response requestToResponse(Request request);
}

MapStruct then should create intermediary methods and use the MappingHelper and invoke the mapDetails method. In case you have multiple methods that map from Request to whatever type details are then you are going to need to used qualified mappings (see more here in the documentation).

It will look something like:

public class MappingHelper {
    @Named("mapDetails") // or the better type safe one with the meta annotation @Qualifier
    public static String mapDetails(Request request);
}

And your mapping will look like:

@Mapper(uses = { MappingHelper.class })
public interface MyMapper {

    @Mappings({
        @Mapping(target = "transaction.process.details", source = "request", qualifiedByName = "mapDetails"), //or better with the meta annotation @Qualifier qualifiedBy
         //more mappings
    })
    Response requestToResponse(Request request);
}


来源:https://stackoverflow.com/questions/46305208/mapstruct-how-to-pass-input-object-to-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!