In Mapstruct, how to ignore null objects and fields

26 Views Asked by At

Dears,

I am using mapstruct in my project(version: 1.5.2.Final, compiler: IncrementalProcessingEnvironment from gradle-language-java-7.6.1.jar, environment: Java 17.0.8).

I am trying to ignore null values but it didn't work. could you help me, please?

enter image description here

Above the picture, packet is null and called packetToPacketDTO, but it is not null in packetToPacketDTO

Also on last picture, effectiveDate should be null but it passes null check.

enter image description here

enter image description here

I want to ignore null values.

My mapper:

@Mapper( nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE )
public interface PacketItemInstanceMapper{


    PacketItemInstanceMapper INSTANCE = Mappers.getMapper( PacketItemInstanceMapper.class );
    PacketItemInstanceDTO toDTO(PacketItemInstance entity);
    List<PacketItemInstanceDTO> toDTO(List<PacketItemInstance> entities);
    default PacketItemInstanceDTO getFirstDTO(List<PacketItemInstance> entities){
        if(CollectionUtils.isEmpty(entities)){
            return null;
        }
        return toDTO(entities.get(0));
    }

}
1

There are 1 best solutions below

0
thunderhook On

This is more of a Hibernate issue. The nullValuePropertyMappingStrategy that you set is what you are looking for.

@Mapper( nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE )

However, as you can see inside the debugger, you are holding a Hibernate proxy (product = {Product$HibernateProxy$X2....}). The getters will load the data behind it, which is not null. You can see this, by evaluating product.getEffectiveDate() in the debugger.

In your case, you may need to unproxy the product, or find another way to load it from the database. See for example this article by Thorben Janssen.