简体   繁体   中英

MapStruct @Mapping(expression="java(...)")

Is it possible to have a condition like an if-else or a Ternary Operator inside the

@Mapping(expression="java(...)")

I have a method that returns the last item of an ArrayList, but in case the list is empty it returns null. I need a condition, so in case I receive the item I can use it, or in case it is null it will map null.

public static MyObjectDetail getLastOne(MyObject myObject) {
    List<MyObjectDetail> details = myObject.getMyObjectDetails();
    if(details.isEmpty()) {
        return null;
    } else {
        return myObject.getLastDetail(myObject);
    }
}

This is the @Mapping that I currently use and it works fine if the list is not empty.

@Mapping(expression = "java(MyObjectDetailMapper.getLastOne(myObject).getNumber())", target = "number"),
    

Solution:

@Mapping(expression = "java(null == MyObjectDetailMapper.getLastOne(myObject) ? null : MyObjectDetailMapper.getLastOne(myObject).getNumber())", target = "number"),
    

Is it good idea to have method if it required for all attributes mappings? if logic is in method I can reuse with each mapping. Please advise.

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