使用場景:兩個領域之間對象轉換。
比如:在系統分層解耦過程中, 對外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()); } }