Set the Null Value for a Target Property in MapStruct | Baeldung
These articles are AI-generated summaries. Please check the original sources for full details.
Set the Null Value for a Target Property in MapStruct | Baeldung
This article explains multiple strategies to ensure a specific property is always set to null during object mapping using MapStruct, a code generation library for Java. The focus is on scenarios where fields like reviewedBy in an entity should be explicitly reset to null when updating from a DTO. The approaches include using expressions, custom methods, @AfterMapping, and handling polymorphic types with @SubclassMapping.
Key Techniques for Setting Null Values
1. Using Expressions
- Purpose: Directly assign
nullto a target field using a Java expression. - Implementation:
@Mapping(target = "reviewedBy", expression = "java(null)") Article toArticleUsingExpression(ArticleDTO dto, Article persisted); - Impact: Ensures the
reviewedByfield is explicitly set tonullduring mapping. Suitable for simple null assignments. - Test Case:
@Test void givenArticleDTO_whenToArticleUsingExpression_thenReturnsArticleWithNullStatus() { // Verifies that 'reviewedBy' is null and 'title' is updated }
2. Using Custom Methods with expression
- Purpose: Reuse logic by defining a method that returns
null. - Implementation:
@Mapping(target = "reviewedBy", expression = "java(getReviewedBy())") default String getReviewedBy() { return null; } - Impact: Promotes reusability if additional logic (e.g., validation) is needed before returning
null.
3. Using qualifiedBy with @Named Methods
- Purpose: Reuse a named method across multiple mappings.
- Implementation:
@Mapping(target = "reviewedBy", qualifiedByName = "toNull") @Named("toNull") default String mapToNull(String property) { return null; } - Impact: Centralizes null logic, reducing redundancy in mapper annotations.
4. Using ignore Property
- Purpose: Leave the target field uninitialized (defaulting to
null). - Implementation:
@Mapping(target = "reviewedBy", ignore = true) Article toArticleUsingIgnore(ArticleDTO dto, Article persisted); - Impact: Works only if the target object is newly created (all fields default to
null). Avoids explicit null assignment.
5. Using @AfterMapping for Post-Processing
- Purpose: Execute logic after mapping completes.
- Implementation:
@AfterMapping default void setNullReviewedBy(@MappingTarget Article article) { article.setReviewedBy(null); } - Impact: Ensures
reviewedByis alwaysnullfor allArticlemappings in the mapper. May cause side effects if used in other methods.
Generalizing for Polymorphic Types
Using @SubclassMapping for Subtypes
- Purpose: Apply null logic to all subtypes of a base class.
- Implementation:
@Mapper public interface ReviewableMapper { @SubclassMapping(source = ArticleDTO.class, target = Article.class) @SubclassMapping(source = WeeklyNewsDTO.class, target = WeeklyNews.class) @Mapping(target = "reviewedBy", expression = "java(null)") Reviewable toReviewable(ReviewableDTO dto); } - Impact: Maps subtypes (e.g.,
ArticleDTOtoArticle) while ensuringreviewedByis alwaysnull. Verified viaisInstanceOf()in tests.
Working Example (Code-Related)
@Mapper
public interface ArticleMapper {
@Mapping(target = "title", source = "dto.title")
@Mapping(target = "id", source = "persisted.id")
@Mapping(target = "reviewedBy", expression = "java(null)")
Article toArticleUsingExpression(ArticleDTO dto, Article persisted);
@AfterMapping
default void setNullReviewedBy(@MappingTarget Article article) {
article.setReviewedBy(null);
}
}
Recommendations (Code-Related)
- Use
expression = "java(null)"for simple null assignments. It is concise and readable. - Prefer
@AfterMappingwhen the null logic must apply to all instances of a mapped type, but be cautious of unintended side effects. - Avoid
ignoreunless the target object is guaranteed to be newly created (as fields default tonull). - Leverage
@SubclassMappingfor polymorphic types to avoid repetitive code across subtypes. - Test thoroughly when using
@AfterMappingorqualifiedByto ensure no unintended behavior in other mapper methods.
Potential Pitfalls
@AfterMappingcan inadvertently modify other fields if the method is not scoped correctly.ignoremay not work as expected if the target object is not newly created (e.g., if it’s a persisted entity with non-null defaults).- Overuse of
qualifiedBymay lead to complex mappings that are hard to maintain.
Reference: Set the Null Value for a Target Property in MapStruct | Baeldung
Continue reading
Next article
Converting Comma-Separated Strings to Int Arrays in Java
Related Content
Mastering @IterableMapping in MapStruct
Learn how @IterableMapping provides granular control over collection mapping with a 90% reduction in boilerplate code.
MapStruct Null Values Handling
Learn different ways to handle null values during object mapping with MapStruct, improving data integrity and application robustness.
Spring Framework 7 and Spring Boot 4 Deliver API Versioning, Resilience, and Null-Safe Annotations
Spring Framework 7 and Spring Boot 4 introduce first-class REST API versioning, JSpecify null safety, and resilience features in November 2025.