MapStruct - How to ignore the unnecessary methods/non-getter-setter methods in the POJO

Viewed 1832

Below is the POJO:

public class TransferObjectListTO {

    private List<A> transferList;

    public List<A> getTransferList() {
        return transferList;
    }

    public void setList(List<A> transferList) {
        this.transferList= transferList;
    }

    public List<A> getList() {
        return getTransferList();
    }

    public void incrementList(List<A> transferList) {
        getTransferList().addAll(transferList);
    }

}

It has a kind of adder method -

incrementList

along with duplicate to getter method -

getList

The Mapstruct generated code has below unnecessary stuff, which adds list, one more time of source type:

if ( targetTypeTransferObjectListTO.getList() != null ) {
    List sourceTypeList = sourceTypeTransferObjectListTO.getList();
    if ( sourceTypeList != null ) {
        targetTypeTransferObjectListTO.getList().addAll( sourceTypeList );
    }
}

We cannot remove these methods - incrementList() and getList() in above POJO because it is used in many places. Now, how can we ignore these methods when mapstruct is generating implementation for mapping?

1 Answers

There are multiple ways that you can achieve what you are looking for. The problem is only with the getList() method, the incrementList() is already ignored by MapStruct.

Ignore the mapping

If you don't have a lot of POJOs that have this pattern and you have few mappers that use this you can just add

@Mapping(target = "list", ignore = true)

Write your own AccessorNamingStrategy

In case you have a lot of POJOs and a lot of mappers then I would suggest you to write your own custom AccessorNamingStrategy that would mark the getList() method as OTHER method.

public class CustomAccessorNamingStrategy extends DefaultAccessorNamingStrategy {

    @Override
    public boolean isGetterMethod(ExecutableElement method) {
        if (method.getSimpleName().toString().equals("getList")) {
            return false;
        } else {
            return super.isGetterMethod(method);
        }
    }
}
Related