Using object-type conversion mapstruct

Conversion between domain objects are common, there are a few times before with BeanUtil miss some fields at some point, but also not flexible enough, so I did not in use.
Then basically convert handwriting classes, but more to feel a lot of trouble. . .
Later discovered mapstruct

maven dependence

    <dependency>
      <groupId>org.mapstruct</groupId>
      <artifactId>mapstruct-jdk8</artifactId>
      <version>1.3.0.Final</version>
    </dependency>
    <dependency>
      <groupId>org.mapstruct</groupId>
      <artifactId>mapstruct-processor</artifactId>
      <version>1.3.0.Final</version>
    </dependency>

Look at how to use it:
First, write two classes A and B

@Data
public class A {
    private String name;
    private int age;
    private Date date;
}
@Data
public class B {
    private String username;
    private int age;
    private String date;
}

Conversion class interface TestConverter, by @Mapping annotation can be more flexible way to customize what you want conversion

@Mapper
public interface TestConverter {
    TestConverter INSTANCE = Mappers.getMapper(TestConverter.class);
    @Mappings({
        @Mapping(source="name", target="username"),
        @Mapping(source="age", target="age"),
        @Mapping(source="date", target="date",dateFormat="yyyy-MM-dd HH:mm:ss")
    })
    B convertA2B(A a);
}

Then rebuild maven project

mvn clean compile

Automatically generated implementation class of a TestConverter

@Generated(
    value = "org.mapstruct.ap.MappingProcessor",
    date = "2019-10-10T16:55:44+0800",
    comments = "version: 1.3.0.Final, compiler: javac, environment: Java 1.8.0_201 (Oracle Corporation)"
)
public class TestConverterImpl implements TestConverter {

    @Override
    public B convertA2B(A a) {
        if ( a == null ) {
            return null;
        }

        B convertB = new B();

        if ( a.getDate() != null ) {
            convertB.setDate( new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ).format( a.getDate() ) );
        }
        convertB.setAge( a.getAge() );
        convertB.setUsername( a.getName() );

        return convertB;
    }
}

Then you can call

public static void main(String[] args) {
        A a = new A();
        a.setAge(13);
        a.setName("luke");
        a.setDate(new Date());
        B b = TestConverter.INSTANCE.convertA2B(a);
        System.out.println(JSON.toJSONString(b));
}

View print the results:

{"age":13,"date":"2019-10-10 17:00:32","username":"luke"}

Guess you like

Origin www.cnblogs.com/feng07/p/11649430.html