Force null value check on field mapping in Mapstruct

Use the nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS) on the mapping property you want to be checked. In this snippet you can see a PostalAdress entity is mapped to an entity of the same type, but the id is overwritten only when it is present in the source:

import java.time.LocalDateTime;

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.NullValueCheckStrategy;

import com.example.entity.PostalAddress;

    componentModel = "cdi",
    imports = {LocalDateTime.class})
public interface PostalAddressEntity2EntityMapperService {

  @Mapping(source = "id", target = "id", nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS)
  PostalAddress toPostalAddressntityToPostalAddressEntity(
      PostalAddress PostalAddress);

This will generate something similar with the following

package com.example.entitytoentity;

import com.example.entity.PostalAddress;
import java.time.LocalDateTime;
import javax.annotation.processing.Generated;
import javax.enterprise.context.ApplicationScoped;

    value = "org.mapstruct.ap.MappingProcessor",
    date = "2021-09-01T14:28:11+0200",
    comments = "version: 1.4.2.Final, compiler: javac, environment: Java 11.0.12 (Azul Systems, Inc.)"
public class PostalAddressEntity2EntityMapperServiceImpl implements PostalAddressEntity2EntityMapperService {

    public PostalAddress toPostalAddressEntity(PostalAddress PostalAddress) {
        if ( PostalAddress == null ) {
            return null;

        PostalAddress PostalAddress1 = new PostalAddress();

        if ( PostalAddress.getId() != null ) {
            PostalAddress1.setId( PostalAddress.getId() );
        PostalAddress1.setStreeNo( PostalAddress.getStreetNo() );
        PostalAddress1.setStreet( PostalAddress.getStreet() );
        PostalAddress1.setMainAdress( PostalAddress.getMainAdress() );

        return PostalAddress1;

Reference -

Shared with from 👉 Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Subscribe to our newsletter for more code resources and news

Adrian Matei (aka adixchen)

Adrian Matei (aka adixchen)
Life force expressing itself as a coding capable human being

Dynamically expand angular material panel when condition met

Dynamically expand angular material panel when condition met code snippet Continue reading

Copy to clipboard with angular material

Published on October 12, 2022