Paul Marcelin Bejan
Paul Marcelin Bejan

Reputation: 1685

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"),
    

Upvotes: 8

Views: 52637

Answers (1)

Paul Marcelin Bejan
Paul Marcelin Bejan

Reputation: 1685

Solution:

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

Mapping expression documentation

Upvotes: 13

Related Questions