标签:
Dozer is a Java Bean to Java Bean mapper that recursively copies data from one object to another. Typically, these Java Beans will be of different complex types.
更多内容见:http://dozer.sourceforge.net/documentation/about.html
两个简单示例:
map --> bean
假设由request得到了页面参数map,想将其转为领域对象–Product。
Product有如下几个属性:
private Long id;
private String name;
private String description;
代码:
// map--> bean
Map<String,Object> map = Maps.newHashMap();
map.put("id", 10000L);
map.put("name", "么么哒");
map.put("description", "金色外壳");
DozerBeanMapper mapper = new DozerBeanMapper();
Product product = mapper.map(map, Product.class);
assertThat(product.getId()).isEqualTo(10000L);
assertThat(product.getName()).isEqualTo("么么哒");
assertThat(product.getDescription()).isEqualTo("金色外壳");
2. bean --> DTO
为了解耦的缘故,会为给第三方提供的接口创建独立的dto对象,而不是复用已有的对应数据库表的实体对象(Entity)。故需要在它们两者之间传输数据。
如现在定义了一个DTO对象,但属性名并不匹配Product对象中的属性名(可能是为了避免冲突或歧义),如下所示:
private long productId;
private String productName;
private String desc;
这时简单的在相关属性上加一个注解即可,如下所示:
@Mapping("id")
private long productId;
@Mapping("name")
private String productName;
@Mapping("description")
private String desc;
完整代码示例见:
Product product = new Product();
product.setId(10001L);
product.setName("Hero");
product.setDescription("黑色外壳");
DozerBeanMapper mapper = new DozerBeanMapper();
ProductDTO productDTO = mapper.map(product, ProductDTO.class);
assertThat(productDTO.getProductId()).isEqualTo(10001L);
assertThat(productDTO.getProductName()).isEqualTo("Hero");
assertThat(productDTO.getDesc()).isEqualTo("黑色外壳");
一个强大易用的java bean之间属性复制框架--Dozer介绍
标签:
原文地址:http://my.oschina.net/zhuguowei/blog/408269