springboot复制bean_Spring Boot bean转换Dozer的快速上手

为什么要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);

每个转换都要写映射?

不!

默认是根据属性名称来匹配的.

快速开始

net.sf.dozer

dozer

5.4.0

测试实体

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官网和其他帖子

本案例参考的帖子

以下省略一堆一堆的帖子

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值