项目地址:https://github.com/mapstruct/mapstruct
说明:mapstruct通过直接生成Getter/Setter方法,所以与原生调用效率基本一致
生成的代码maven是在 target\generated-sources\annotations 目录。
依赖
同时用到了lombok
<lombok.version>1.18.12</lombok.version>
<org.mapstruct.version>1.4.2.Final</org.mapstruct.version>
<m2e.apt.activation>jdt_apt</m2e.apt.activation>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${org.mapstruct.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>${org.mapstruct.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${org.mapstruct.version}</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${org.mapstruct.version}</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
示例
//class MpsVOMp
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
@Mapper(componentModel = "spring")
//@Mapper
public interface MpsVOMp {
/**
* 用来调用实例 实际开发中可使用注入Spring 不写
*/
MpsVOMp CAR_MAPPING = Mappers.getMapper(MpsVOMp.class);
/**
* 源类型 目标类型 成员变量相同类型 相同变量名 不用写{@link org.mapstruct.Mapping}来映射
*/
@Mapping(source = "string1", target = "string2")
@Mapping(source = "fromVo", target = "toVo")
MpsToVO mapper(MpsFromVO fromVO);
}
//class MpsFromVO
import java.math.BigDecimal;
import java.util.Date;
import lombok.Data;
@Data
public class MpsFromVO {
private int int1;
private Integer int2;
private long long1;
private Long long2;
private double double1;
private BigDecimal double2;
private String string1;
private Date date1;
private boolean bool1;
private Boolean bool2;
private MpsFromVO fromVo;
}
//class MpsToVO
import java.math.BigDecimal;
import java.util.Date;
import lombok.Data;
@Data
public class MpsToVO {
private int int1;
private Integer int2;
private long long1;
private Long long2;
private double double1;
private BigDecimal double2;
private String string1;
private Date date1;
private boolean bool1;
private Boolean bool2;
//
private String string2;
private MpsToVO toVo;
}