MapStruct @Mapping(expression="java(...)")
Asked Answered
O

1

6

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"),
    
Ozalid answered 26/6, 2020 at 14:31 Comment(0)
O
11

Solution:

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

Mapping expression documentation

Ozalid answered 30/6, 2020 at 12:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.