Dozer是一個JavaBean到JavaBean之間的轉換工具。它就可以遞歸的將數(shù)據(jù)從一個對象復制到另一個對象溢吻。
Dozer的官方文檔:http://dozer.sourceforge.net/documentation/whymap.html
Dozer的github地址:https://github.com/DozerMapper/dozer
Dozer轉換好處:
- 如果兩個類型屬性名稱一致维费,不論類型是否一致。dozer都可以自動配置
- 如果類中有null property促王,dozer可以默認將屬性指為null犀盟,不會拋出nullPointerExeception異常。
Dozer整合項目(有三種:xml形式/注解配置/API配置)
引入jar
<dependency>
<groupId>net.sf.dozer</groupId>
<artifactId>dozer</artifactId>
<version>5.4.0</version>
</dependency>
xml配置
- xml頭部文件
<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://dozer.sourceforge.net
http://dozer.sourceforge.net/schema/beanmapping.xsd">
</mappings>
xml中mapping配置(將a中對應的屬性名轉換為b中對應的屬性名蝇狼,<a>標簽轉換為<b>標簽)
<mapping>
<class-a>com.qding.brick.pojo.biz.Project</class-a>
<class-b>com.qding.openapi.call.stage.struct.Project</class-b>
<field>
<a>id</a>
<b>projectId</b>
</field>
<field>
<a>name</a>
<b>projectName</b>
</field>
<field>
<a>address</a>
<b>addr</b>
</field>
</mapping>
注:官網(wǎng)著重建議:在現(xiàn)實應用中阅畴,最好不要每次映射對象時都創(chuàng)建一個Mapper實例來工作,這樣會產(chǎn)生不必要的開銷迅耘。如果你不使用IoC容器(如:spring)來管理你的項目恶阴,那么,最好將Mapper定義為單例模式豹障。
- 測試:
Mapper mapper = new DozerBeanMapper();
DestinationObject destObject = mapper.map(sourceObject, DestinationObject.class);
- 補充:單例模式例子
public class DozerMapperConstant {
private static final Mapper mapper= new org.dozer.DozerBeanMapper();
public static DozerBeanMapper getDozerBeanMapper() {
return mapper;
}
}
Mapper announcementDozerMapper = DozerMapperConstant.dozerMapper;
API方式
import static org.dozer.loader.api.FieldsMappingOptions.*;
import static org.dozer.loader.api.TypeMappingOptions.*;
...
BeanMappingBuilder builder = new BeanMappingBuilder() {
protected void configure() {
mapping(Bean.class, Bean.class,
TypeMappingOptions.oneWay(),
mapId("A"),
mapNull(true)
)
.exclude("excluded")
.fields("src", "dest",
copyByReference(),
collectionStrategy(true,
RelationshipType.NON_CUMULATIVE),
hintA(String.class),
hintB(Integer.class),
FieldsMappingOptions.oneWay(),
useMapId("A"),
customConverterId("id")
)
.fields("src", "dest",
customConverter("org.dozer.CustomConverter")
);
}
};
使用
DozerBeanMapper mapper = new DozerBeanMapper();
mapper.addMapping(builder);
注解方式 (mapping自動注入)
a類
public class SourceBean {
private Long id;
private String name;
@Mapping("binaryData")
private String data;
@Mapping("pk")
public Long getId() {
return this.id;
}
public String getName() {
return this.name;
}
}
b類
public class TargetBean {
private String pk;
private String name;
private String binaryData;
public void setPk(String pk) {
this.pk = pk;
}
public void setName(String name) {
this.name = name;
}
}