Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Mapstruct" Is there a way to map an empty String to null using mapstruct?

Tags:

java

mapstruct

I am using MapStruct for mapping a DTO to an entity and vice versa in my Spring Boot application.

Is there a way to map empty strings to null using @Mapping?

like image 378
Saurabh Gupta Avatar asked Apr 16 '20 11:04

Saurabh Gupta


People also ask

How do I ignore unmapped properties in MapStruct?

We can ignore unmapped properties in several mappers by setting the unmappedTargetPolicy via @MapperConfig to share a setting across several mappers.

Does MapStruct use reflection?

During compilation, MapStruct will generate an implementation of this interface. This implementation uses plain Java method invocations for mapping between source and target objects, i.e. no reflection or similar.

What is the use of MapStruct?

MapStruct is a code generator tool that greatly simplifies the implementation of mappings between Java bean types based on a convention over configuration approach. The generated mapping code uses plain method invocations and thus is fast, type-safe, and easy to understand.


Video Answer


2 Answers

Using an expression, as suggested in another answer, is possible. I personally prefer to do this a bit safer, and perhaps a bit more declarative.

@Mapper
public interface MyMapper {

    @Mapping( target = "s2",  qualifiedBy = EmptyStringToNull.class )
    Target map( Source source);

    @EmptyStringToNull
    default String emptyStringToNull(String s) {
        return s.isEmpty() ? null : s;
    }

    @Qualifier
    @java.lang.annotation.Target(ElementType.METHOD)
    @Retention(RetentionPolicy.CLASS)
    public @interface EmptyStringToNull {
    }

    class Source {

        private String s1;
        private String s2;

        public String getS1() {
            return s1;
        }

        public void setS1(String s1) {
            this.s1 = s1;
        }

        public String getS2() {
            return s2;
        }

        public void setS2(String s2) {
            this.s2 = s2;
        }
    }

    class Target {

        private String s1;
        private String s2;

        public String getS1() {
            return s1;
        }

        public void setS1(String s1) {
            this.s1 = s1;
        }

        public String getS2() {
            return s2;
        }

        public void setS2(String s2) {
            this.s2 = s2;
        }
    }
}


You can re-use the EmptyStringToNull qualifier as many times as you'd like and your not dependent on the parameter name.

like image 147
Sjaak Avatar answered Sep 21 '22 13:09

Sjaak


You can simply use the expression within the @Mapping

@Mapping(target = "name", expression = "java(source.name.isEmpty() ? null : source.name)")
Dog convert(Cat source);
like image 29
Daniel Taub Avatar answered Sep 25 '22 13:09

Daniel Taub