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

12,984

Solution:

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

Related videos on Youtube

Paul Marcelin Bejan
Author by

Paul Marcelin Bejan

Updated on June 04, 2022

Comments

  • Paul Marcelin Bejan
    Paul Marcelin Bejan almost 2 years

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