how to exclude whole property if they are null from Modelmapper
Asked Answered
S

1

5

Does ModelMapper(http://modelmapper.org/) support what exclude property? If the value is null.

I just found PropertyMap out. but It is a constraint to me. because I have to describe a specific property that I want.

Like this.

ModelMapper modelMapper = new ModelMapper();
modelMapper.addMappings(new PropertyMap<TestObject, TestObject>() {
    @Override
    protected void configure() {
        when(Conditions.isNull()).skip().setName(source.getName());
        when(Conditions.isNull()).skip().set...(source.get...());
        when(Conditions.isNull()).skip().set...(source.get...());
        when(Conditions.isNull()).skip().set...(source.get...());
        when(Conditions.isNull()).skip().set...(source.get...());
        when(Conditions.isNull()).skip().set...(source.get...());
    }
});

In my case, I have a lot of property and verbose. How to exclude mapping property if they are null from all them. Is there more comfortable solution?

thanks.

Suellen answered 2/8, 2017 at 3:36 Comment(0)
A
24

You can configure ModelMapper to ignore all properties that are null with the following configuration:

modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());

It is useful, for example, for partial updates of a target object where you only want to copy those properties from the source object that are not null.

Acima answered 21/2, 2018 at 15:9 Comment(5)
Thanks, That's I wanted.Suellen
This isn't working for me idk why :( #56359927Pontius
I have int fields in my DTO/Entity. Since int can only be a zero, and cannot be null, is there a way to skip values that are equal to zero ?Biquadrate
@Biquadrate you can use the Integer wrapper class instead of int primitive typeWitham
Is there any solution of int fields if they are coming from third party jar and can not be modified.Shupe

© 2022 - 2024 — McMap. All rights reserved.