Java bean mappings, the easy way!
导入依赖
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.4.2.Final</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.4.2.Final</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>1.4.2.Final</version>
</dependency>
实体:
@Data
public class Address {
private String province;
private String city;
private String area;
}
@Data
@AllArgsConstructor
public class User {
private String name;
private String password;
private Address address;
}
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class UserCopy implements Serializable {
private static final long serialVersionUID = -640535309004188173L;
private String name;
private String password;
private Address address;
public static void main(String[] args) {
User user3 = new User("name", "password", new Address("province", "city", "area"));
UserCopy userCopy3 = UserCopyConverter.INSTANCE.userConvertUserCopy(user3);
userCopy3.getAddress().setProvince("new setProvince");
userCopy3.setName("new name");
System.err.println(user3.toString());
System.err.println(userCopy3.toString());
}
}
Mapper 接口文件:
@Mapper
public interface UserCopyConverter {
UserCopyConverter INSTANCE = Mappers.getMapper(UserCopyConverter.class);
UserCopy userConvertUserCopy(User user);
}
输出结果:
User(name=name, password=password, address=Address(province=new setProvince, city=city, area=area))
UserCopy(name=new name, password=password, address=Address(province=new setProvince, city=city, area=area))
拷贝结果为浅拷贝
mapstruck的实现是会自动生成一个实现类:
public class UserCopyConverterImpl implements UserCopyConverter {
public UserCopyConverterImpl() {
}
public UserCopy userConvertUserCopy(User user) {
if (user == null) {
return null;
} else {
UserCopy userCopy = new UserCopy();
userCopy.setName(user.getName());
userCopy.setPassword(user.getPassword());
userCopy.setAddress(user.getAddress());
return userCopy;
}
}
}