背景:
在业务代码中,会出现很多dto之间的相互转换,就是两个dto属性的各种get,set,会造成大量的冗余代码,所以出现了一些工具,比如Spring中的beanUtil,但是beanutil是运行时处理的,性能较差,所以出现了一款利器,mapstruct,它是编译生效的,类似lombok,所以性能大大提升
maven导入:
org.mapstruct mapstruct 1.2.0.Final org.mapstruct mapstruct-processor 1.2.0.Final
建立两个类,一个UserEntity,一个UserDTO
@Datapublic class UserEntity { private String name; private String password; private Integer age; private Date birthday; private String sex;}
@Datapublic class UserVO { private String name; private String age; private String birthday; private String gender;}
接下来是关键的映射,UserMapper接口
@Mapperpublic interface UserMapper { UserMapper INSTANCE = Mappers.getMapper(UserMapper.class); /** * 1、entity与vo中属性名相同时候默认映射,(比如name),属性名相同属性类型不同也会映射,(比如birthday,一个Data,一个String) * 2、entity与vo中属性名不同的,需要通过@Mapping明确关系来形成映射(如sex对应gender) * 3、无映射关系属性被忽略(如UserEntity的password) */ @Mappings({ @Mapping(target = "gender", source = "sex"), }) UserVO entityToVO(UserEntity entity);}
测试代码
public class UserTest { public static void main(String[] args) { UserEntity userEntity = new UserEntity(); userEntity.setAge(1); userEntity.setName("snow"); userEntity.setPassword("123"); userEntity.setSex("男"); userEntity.setBirthday(new Date()); UserVO userVO = UserMapper.INSTANCE.entityToVO(userEntity); System.out.println(userVO); System.out.println("================="); System.out.println(userEntity); }}
结果如下:
UserVO(name=snow, age=1, birthday=18-5-11 下午9:23, gender=男)=================UserEntity(name=snow, password=123, age=1, birthday=Fri May 11 21:23:34 CST 2018, sex=男)
以上是简单举例,参考https://blog.csdn.net/OO570741825/article/details/78530022,在它基础上做了些修正