Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
Set null to target using mastruct

I am using mapstruct and I am wondering if there are any ways to set null value for some target properties. For example,

public class MySource {
    private String prop1;
    private String prop2;

    public MySource() {
        // Initialization.
    }

    // Getters - Setters.
}

public class MySourceDto {
    private String prop1;
    private String prop2;

    public MySourceDto() {
        // Initialization.
    }

    // Getters - Setters.
}

@Mapper
public interface MySourceMapper {

    @Mappings({
        @Mapping(target = "prop1", propertyToSetNull = null)})
    public MySourceDto toView(MySource mySource);

}

I would love the above source, dto and mapper to generate the below source code,

@Component
public class MySourceMapperImpl implements MySourceMapper {

    @Override
    public MySourceDto toView(MySource mySource) {
        if ( mySource == null ) {
            return null;
        }

        MySourceDto mySourceDto = new MySourceDto();

        mySourceDto.setProp1( mySource.getId() );
        mySourceDto.setProp2( null );

        return mySourceDto;
    }
}
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can use @Mapping(target = "prop1", expression = "java(null)") to achieve that.

You can find more information about expression in the reference guide here.

Currently only java is supported as an expression language, MapStruct will just take what you have written within the brackets and directly apply it to the setter, the implementation will look exactly like in your example.

about 4 years ago · Santiago Trujillo Report

0

Also you can ignore mapping of this property:

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

this will set this value to default which is null in your case

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!