Mapping DTO an Entity, leave entity null if all your field is null

My entity is return fields null example: EntityTest{id=null, name=null}

but I need that if all fields are null return EntityTest = null

TestEntity

@Entity
@Table(name="TestEntity")
public class TestEntity {
    @Id
    @Column(name="id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(name="test_name")
    private String testName;
}

TestEntityDto

public class TestEntityDto {

    private long id;
    private String test_name;
}

TestEntityMapper

@Mapper
public interface TestEntityMapper {
    TestEntity TestEntityDTOToTestEntity(TestEntityDTO testEntityDTO);

Implementa

testEntityDTO.setId(null);
testEntityDTO.setNameTest(null);
TestEntity testEntity = TestEntityMapper.TestEntityDTOToTestEntity(testEntityDTO);

Actual Result:

EntityTest{id=null, name=null}

Expected Result:

EntityTest = null

Solution 1:

In the upcoming 1.5 release MapStruct is adding support for conditional mapping. In the current released Beta2 of 1.5 there is no support for conditional support parameters. However, there is an open enhancement request to add this for source parameters.

What this means is that you can do something like:

public class MappingUtils {

    @Condition
    public static boolean isPresent(TestEntityDTO dto) {
        if (dto == null) {
            return false;
        }

        return dto.getId() != null || dto.getName() != null;
    }

}

Which means that you can have a mapper like:

@Mapper(uses = MappingUtils.class)
public interface TestEntityMapper {

    TestEntity testEntityDTOToTestEntity(TestEntityDTO testEntityDTO);

}

and the implementation will look like:

public class TestEntityMapperImpl implements {

    @Override
    public TestEntity testEntityDTOToTestEntity(TestEntityDTO dto) {
        if (!MappingUtils.isPresent(dto)) {
            return null
        }

        // the rest of the mapping
    }
}

Note: this is not yet possible in a release version, but this is how it will work. Apart from this future solution there is no other solution out-of-the-box with MapStruct.