在实际项目开发过程中,总有数据实体类互相转换的需求,DO、BO、VO、DTO等数据模型转换经常发生。今天推荐几个好用的实体类转换工具,分别是EntityUtils
MapStruct
BeanCopier
,并且给出使用的案例。需要说明的是,本文有配套视频讲解。
下面分别讲解这3种工具的使用。
学习工具包源代码的朋友,请看这里。
<dependency>
<groupId>xin.altitude.cmsgroupId>
<artifactId>ucode-cms-commonartifactId>
<version>1.5.8version>
dependency>
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "tb_user")
public class User {
private static final long serialVersionUID = 1L;
@TableId(type = IdType.AUTO)
private Long userId;
private String userName;
private Integer age;
private Long deptId;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime gmtCreate;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime gmtModified;
public User(User user) {
if (Objects.nonNull(user)) {
this.userId = user.userId;
this.userName = user.userName;
this.age = user.age;
this.deptId = user.deptId;
this.gmtCreate = user.gmtCreate;
this.gmtModified = user.gmtModified;
}
}
}
@Data
@NoArgsConstructor
public class UserVo extends User {
private String deptName;
private String tel;
/**
* 原生构造器来实现 DO 转 VO
*
* @param user
*/
public UserVo(User user) {
super(user);
}
}
public List<UserVo> selectUserList1() {
List<User> userList = this.list();
// 一行代码完成实体类转换
List<UserVo> userVoList = EntityUtils.toList(userList, UserVo::new);
return userVoList;
}
说明一下,使用EntityUtils
工具类最主要的是处理DO、VO等数据类构造器。
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.5.3.Final</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.3.Final</version>
</dependency>
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "tb_user")
public class User {
private static final long serialVersionUID = 1L;
@TableId(type = IdType.AUTO)
private Long userId;
private String userName;
private Integer age;
private Long deptId;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime gmtCreate;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime gmtModified;
}
@Data
@NoArgsConstructor
public class UserVo extends User {
private String deptName;
private String tel;
}
@org.mapstruct.Mapper
public interface UserMapStrcut {
UserVo toUserVo(User user);
List<UserVo> toUserVo(List<User> user);
}
public List<UserVo> selectUserList2() {
List<User> userList = this.list();
UserMapStrcut mapper = Mappers.getMapper(UserMapStrcut.class);
return mapper.toUserVo(userList);
}
BeanCopier
在Spring体系下无额外依赖,DO和VO数据类同MapStruct部分。
public List<UserVo> selectUserList3() {
List<User> userList = this.list();
BeanCopier beanCopier = BeanCopier.create(User.class, UserVo.class, false);
List<UserVo> rs = new ArrayList<>();
for (User user : userList) {
UserVo userVo = new UserVo();
beanCopier.copy(user, userVo, null);
rs.add(userVo);
}
return rs;
}
本文介绍的三种实体类转换工具是非常高效的,相比于以反射为基础的实现来说,性能相当出色。数据模型这块在程序运行过程中会创建大量对象,因此既要考虑开发的灵活性,也要注重运行性能。