为什么要bean转换
看图
大白话来说就是,我有的不是你想要的,那就只能通过转换成你想要再给到你.
分这么多只有一点差异的实体有必要吗? 有,这点麻烦会解决太多问题了.
例如:
1.比如添加了@RestController返回json格式数据会把返回的实体进行序列化.会触发所有懒加载.(懒加载形同虚设)
2.一个持久实体 包含 密码 字段,不好频繁的把实体的密码去掉再给到 前端. 需要 po -> vo.
3.自己的实体需要改成别人的实体类型(比如接其他系统),但是格式名称不一样.需要 ?? -> dto.
还有.......(以下省略1k文本)
但是以上实现都需要各种set set set(一万个set),怎么解决?
Dozer
大白话:dozer是一个能把实体和实体之间进行转换的工具.只要建立好映射关系.就像是ORM的数据库和实体映射一样.
// entity -> entityVo
EntityVo entityVo = dozerMapper.map(entity, entityVo);
每个转换都要写映射?
不!
默认是根据属性名称来匹配的.
快速开始
<dependency>
<groupId>net.sf.dozer</groupId>
<artifactId>dozer</artifactId>
<version>5.4.0</version>
</dependency>
测试实体
import lombok.Data;
import org.dozer.Mapping;
import java.util.Date;
/**
* @author: ZGC
* @date Created in 2018/9/1 上午 11:49
*/
//@Data
public class TestEntity {
private Long id;
/**
* 属性
*/
@Mapping("theirProperty")
private String myProperty = "";
/**
* 标题
*/
private String title = "";
/**
* 密码
*/
private String password = "";
private Date createAt;
private Date updatedAt;
// 本案列.省略getting setting方法.......
}
测试vo实体
import lombok.Data;
/**
* @author: ZGC
* @date Created in 2018/9/1 上午 11:35
*/
@Data
public class TestEntityVo {
/**
* 属性 另一边的 myProperty 通过@Mapping("theirProperty")映射到这个字段
*
* TestEntity.myProperty -> TestEntityVo.theirProperty
*/
private String theirProperty = "";
/**
* 标题 默认的映射
*
* TestEntity.title -> TestEntityVo.title
*/
private String title = "";
/**
* 密码(不展示)
*
* 直接不写 就不会映射
*/
// String password = "";
// private Long id;
// private Date createAt;
// private Date updatedAt;
}
加个bean到spring容器中
import org.dozer.DozerBeanMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author: ZGC
* @date Created in 2018/8/31 下午 7:39
*/
@Configuration
public class DozerBeanMapperConfigure {
@Bean
public DozerBeanMapper mapper() {
DozerBeanMapper mapper = new DozerBeanMapper();
return mapper;
}
}
注入然后开始使用啦
@Autowired
protected Mapper dozerMapper;
@Test
public void test() {
TestEntity testEntity = new TestEntity();
testEntity.setMyProperty("testEntity.MyProperty");
testEntity.setTitle("testEntity.title");
testEntity.setPassword("6asd5f46asd8f746a8df74");
System.out.println(testEntity);
// convert bean
TestEntityVo convert = dozerMapper.map(testEntity, TestEntityVo.class);
System.out.println(TestEntityVo);
}
TestEntity(id=null, myProperty=testEntity.MyProperty, title=testEntity.title, password=6asd5f46asd8f746a8df74, createAt=null, updatedAt=null)
TestEntityVo(theirProperty=testEntity.MyProperty, title=testEntity.title)
Okay, your demo's done
本案例只是简易快速上手教程,详细的内容和复杂映射请看dozer官网和其他帖子
本案例参考的帖子
banjuer 的 Springboot整合Dozer深度复制
hollischuang 的 使用Dozer优雅的将DO转换成VO
以下省略一堆一堆的帖子