MapStruct使用和原理分析
阿新 • • 發佈:2020-12-26
在程式碼開發中,經常會遇到不同實體類之間的欄位copy,以前經常用到的有通過set賦值或者apache、spring的BeanUtils.copyProperties(),原生的set賦值隨便速度比較快,但是當欄位多的時候,就顯得比較麻煩了,每個都要自己手動set一下值,而apache、spring的BeanUtils.copyProperties()可以解決這種欄位比較多的情況,但是這種方式有個弊端,就是,欄位的型別和名稱都必須一樣才可以,否則copy時會被忽略掉。知道接觸了一種新的方式,使用MapStruct方式。
加入MapStruct的依賴jar包
<properties> <mapstruct.version>1.2.0.Final</mapstruct.version> </properties> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-jdk8</artifactId> <version>${mapstruct.version}</version> </dependency> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>${mapstruct.version}</version> </dependency>
建立實體類User
public class User { private Integer id; private String userName; private String desc; private Integer age; private Double salary; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } }
建立UserDTO類
public class UserDTO {
private Integer id;
private String userName;
private Date createDate;
private String remark;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public UserDTO() {
}
@Override
public String toString() {
return "UserDTO{" +
"id=" + id +
", userName='" + userName + '\'' +
", createDate=" + createDate +
", remark='" + remark + '\'' +
'}';
}
建立介面UserMapStruct
import org.mapstruct.MapMapping;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
@Mapper
public interface UserMapStruct {
UserMapStruct INSTANCE = Mappers.getMapper(UserMapStruct.class);
@Mappings({
@Mapping(source = "desc",target = "remark")
})
public UserDTO userToDto(User user);
}
程式碼測試
public class TestUserMapStruct {
public static void main(String[] args) {
User user = new User();
user.setId(1000);
user.setAge(21);
user.setDesc("測試複製工具");
user.setSalary(400.44);
user.setUserName("張三");
UserDTO userDTO = UserMapStruct.INSTANCE.userToDto(user);
System.out.println(userDTO.toString());
}
}
輸出結果