使用场景:两个领域之间对象转换。
比如:在系统分层解耦过程中, 对外facade接口,一般使用VO对象,而内core业务逻辑层或者数据层通常使用Entity实体。
VO对象
package com.maven.demo; public class ProductVO{ private Long id; private String name; private String description; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
实体对象
package com.maven.demo; import org.dozer.Mapping; public class ProductEntity { @Mapping("id") private long productId; @Mapping("name") private String productName; @Mapping("description") private String desc; public long getProductId() { return productId; } public void setProductId(long productId) { this.productId = productId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } }
Dozer使用测试:
package com.maven.demo; import java.util.HashMap; import java.util.Map; import org.dozer.DozerBeanMapper; import org.junit.Test; import static org.junit.Assert.assertEquals; public class Demo{ /** * map->bean */ @Test public void testDozer1() { Map<String,Object> map = new HashMap(); map.put("id", 10000L); map.put("name", "小兵"); map.put("description", "帅气逼人"); DozerBeanMapper mapper = new DozerBeanMapper(); ProductVO product = mapper.map(map, ProductVO.class); assertEquals("小兵",product.getName()); assertEquals("帅气逼人",product.getDescription()); assertEquals(Long.valueOf("10000"), product.getId()); } /** * VO --> Entity (不同的实体之间,不同的属性字段进行复制) */ @Test public void testDozer2(){ ProductVO product = new ProductVO(); product.setId(10001L); product.setName("xiaobing"); product.setDescription("酷毙了"); DozerBeanMapper mapper = new DozerBeanMapper(); ProductEntity productEntity = mapper.map(product, ProductEntity.class); assertEquals("xiaobing",productEntity.getProductName()); } }