首頁  >  文章  >  类库下载  >  使用Dozer優雅的將DO轉換成VO

使用Dozer優雅的將DO轉換成VO

高洛峰
高洛峰原創
2016-10-15 13:42:362731瀏覽

什麼是DO、DTO和VO

在Java中 VO、 PO、DO、DTO、 BO、 QO、DAO、POJO的概念中介紹過Java中的各種模型概念。
在這裡簡單再總結一下:

在日常的專案開發中,VO對應於頁面上需要顯示的資料(表單),DO對應於資料庫中儲存的資料(資料表),DTO對應於除二者之外需要進行傳遞的資料。

很多人可能對VO和DTO並不是那麼熟悉,相反對DO卻比較熟悉,那是因為在很多項目中由於種種原因我們只使用了DO,原因可能有以下幾種:

1、項目太小,對於一種業務實體,封裝成一個DO就夠了。

2、並不熟悉DTO、VO,更不知道他們之間的差異。

3、了解DODTOVO之間的差別,但是懶得用。

那麼,這裡,部落客再囉嗦為什麼要引入這麼多概念,為什麼我要建議大家在自己的專案中使用這些實體物件。

為什麼不能只用一個DO

我們來看這樣一個例子。假如我們的專案中由User這樣一個實體。我們在建立User表的時候一般都包含一下屬性:

使用Dozer優雅的將DO轉換成VO

針對這個實體,我們通常需要建立一個DO類,用來封裝這個User實體。

public class UserDO {
    private Integer id;                 //唯一主键
    private Date createdTime;           //创建时间
    private Date updatedTime;           //最后更新时间
    private String name;                //姓名
    private Integer age;                //年龄
    private String gender;              //性别
    private String address;             //住址
    private String password;            //密码
    private String nickName;            //昵称
    private Date birthday;              //生日
    private String politicalStatus;     //政治面貌,1表示群众,2表示团员,3表示党员,4表示其他,100表示未知
    private Integer companyId;          //公司的ID
    private Integer status;             //数据状态,1表示可用,0表示不可用
 
    //setter and getter
}

然後,在程式碼中,從DAO一直到前端展示,我們都透過這個UserDO類別的物件來進行資料傳輸。這樣做會有什麼問題嘛?

不需要的欄位也會傳遞到前端頁面。

如password、createdTime、updatedTime和status這幾個字段我們可能在前端根本不需要展示,但是這些字段有可能也會被傳遞到前端(除非我們在SQL查詢的時候沒有查詢出對應的字段)。這不僅使資料的傳輸量增大,還可能有安全性問題。

某些欄位需要轉換,但是無法支援。

對於上面例子中的政治面貌字段,我們在資料庫中存儲的是數字,但是在前端頁面我要展示的是中文描述。這種情況只能在前端透過if/else的方式來分割情況展示。

某些欄位要展示,但是並不希望出現在資料庫中

在User表中我們只保存了這個使用者的companyId,需要同時查詢company表來查詢出該公司的更多詳細資料。對於User對象,如果我們想在前端同時展示他所屬的公司,希望透過一次查詢全都查出來怎麼辦?有幾個簡單的方案,第一個是讓UserDO中包含一個Company類別的屬性,透過這個屬性來傳遞。另外一種是把我們希望傳到前端的Company的屬性也寫到UserDO。但是,如果真的這麼做了,那UserDO還能被稱為DO了嗎?

還有很多問題,這裡就不詳細介紹了。

可見,使用一個DO從頭到尾(從資料庫到前端頁面)並不是一種好的設計。

如何正確的使用DO、DTO、VO

對於上面的例子,我們可以將他設計成以下類別。由於模型並不複雜,這裡只需要再引入VO就可以了。

UserDO已經和資料庫欄位一一對應了,這裡不需要修改。

public class UserDO {
    private Integer id;                 //唯一主键
    private Date createdTime;           //创建时间
    private Date updatedTime;           //最后更新时间
    private String name;                //姓名
    private Integer age;                //年龄
    private String gender;              //性别
    private String address;             //住址
    private String password;            //密码
    private String nickName;            //昵称
    private Date birthday;              //生日
    private String education;           //学历
    private String politicalStatus;     //政治面貌,1表示群众,2表示团员,3表示党员,4表示其他,100表示未知
    private Integer companyId;          //公司的ID
    private Integer status;             //数据状态,1表示可用,0表示不可用
 
    //setter and getter
}

引入UserVO,用於封裝傳遞到前端需要展示的欄位。

public class UserVO {
    private Integer id;                 //唯一主键
    private String name;                //姓名
    private Integer age;                //年龄
    private String gender;              //性别
    private String address;             //住址
    private String nickName;            //昵称
    private Date birthday;              //生日
    private String education;           //学历
    private String politicalStatus;     //政治面貌,群众、团员、党员等
    private Company company;            //公司
 
    //setter and getter
}

UserVO中只包含了展示所需的字段,並不需要展示的字段在這裡不需要包含。

在引入了這個類別之後,我們就可在進行資料庫查詢的時候使用UserDO,然後再需要傳遞到前端的時候把DO轉換成VO。

總結

看到這裡,你可能已經發現,UserDO和UserVO中包含了大量的相同欄位。難道真的有必要再單獨設計VO嘛?我可以明確告訴你的是,當你的系統越來越大,表格中的欄位越來越多的時候,使用DODTOVO等概念進行分層處理是絕對有好處的。至於如何進行有效的在不同的實體類別間進行轉換是我接下來要介紹的。

優雅的將DO轉換成VO

Dozer 是一個物件轉換工具。

Dozer可以在JavaBean到JavaBean之间进行递归数据复制,并且这些JavaBean可以是不同的复杂的类型。
所有的mapping,Dozer将会很直接的将名称相同的fields进行复制,如果field名不同,或者有特别的对应要求,则可以在xml中进行定义。

前面我们介绍的DO\DTO\VO不就是JavaBean嘛。正好可以使用Dozer进行转换呀。
除了使用Dozer,当然你还由其他选择:

典型的解决方案就是手动拷贝,弊端很明显,代码中充斥大量Set 和Get方法,真正的业务被埋藏值与值的拷贝之中。

另一种方案就是使用BeanUtil,但BeanUtil不够很好的灵活性,又时候还不得不手动拷贝。Dozer可以灵活的对对象进行转换,且使用简单。

Dozer 支持的转换类型

Primitive 基本数据类型 , 后面带 Wrapper 是包装类 Complex Type 是复杂类型

•   Primitive to Primitive Wrapper 
•   Primitive to Custom Wrapper 
•   Primitive Wrapper to Primitive Wrapper 
•   Primitive to Primitive 
•   Complex Type to Complex Type 
•   String to Primitive 
•   String to Primitive Wrapper 
•   String to Complex Type if the Complex Type contains a String constructor 
•   String 到复杂类型 , 如果复杂类型包含一个 String 类型的构造器 
•   String to Map 
•   Collection to Collection 
•   Collection to Array 
•   Map to Complex Type 
•   Map to Custom Map Type 
•   Enum to Enum 
•   Each of these can be mapped to one another: java.util.Date, java.sql.Date, java.sql.Time, java.sql.Timestamp, java.util.Calendar, java.util.GregorianCalendar 
•   String to any of the supported Date/Calendar Objects. 
•   Objects containing a toString() method that produces a long representing time in (ms) to any supported Date/Calendar object.

在普通Java项目中使用Dozer

在pom.xml中增加依赖

<dependency>
  <groupId>net.sf.dozer</groupId>
  <artifactId>dozer</artifactId>
  <version>5.5.1</version>
</dependency>

使用Dozer进行类转换

public class Main {
 
    public static void main(String[] args) {
        DozerBeanMapper mapper = new DozerBeanMapper();
        UserDO userDO = new UserDO();
        userDO.setName("hollis");
        userDO.setAddress("hz");
        userDO.setAge(25);
        userDO.setCompanyId(1);
        userDO.setBirthday(new Date());
        userDO.setGender("male");
        userDO.setEducation("1");
        userDO.setNickName("hollis");
        userDO.setPoliticalStatus("3");
        UserVO userVO = (UserVO) mapper.map(userDO, UserVO.class);
        System.out.println(userVO);
    }
}

特殊的字段转换
在使用mapper进行转换前,设置一个或多个mapping文件

List myMappingFiles = new ArrayList();    
myMappingFiles.add("dozer-mapping.xml");    
mapper.setMappingFiles(myMappingFiles);

配置dozer-mapping.xml文件

数据类型不一致,或者名称不相同或者有级联关系等情况下,可以通过文件dozer-mapping.xml来进行定制Bean的转换

<?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">
 
    <mapping>
        <class-a>com.hollis.lab.UserDO</class-a>
        <class-b>com.hollis.lab.UserVO</class-b>
    </mapping>
</mappings>

在JavaWeb项目中使用Dozer

在pom.xml中增加依赖

<dependency>
  <groupId>net.sf.dozer</groupId>
  <artifactId>dozer</artifactId>
  <version>5.5.1</version>
</dependency>

使用Spring集成dozer

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="baseMapper" class="org.dozer.spring.DozerBeanMapperFactoryBean">
        <property name="mappingFiles">
            <list>
                <value>classpath:mapping/dozer-mapping.xml</value>
            </list>
        </property>
    </bean> 
</beans>

使用baseMapper进行Bean的转换

@Autowired
private Mapper baseMapper;
private UserVO doToVo(UserDO userDO){
    if(userDO == null) return null;
    UserVO vo = baseMapper.map(userDO, UserVO.getClass());
    if(userDO.getCompanyId != null) getCompany(vo);
    return vo;
}

通过以上的代码加配置,我们就实现了从DO转换到VO的部分操作,之所以说是部分操作,是因为我们在dozer-mapping.xml并没有做多余的配置,只是使用dozer将DO中和VO中共有的属性转换了过来。对于其他的类型不同或者名称不同等的转换可以参考官网例子通过设置dozer-mapping.xml文件来实现。

上面还有一个getCompany()没有实现。这个方法其实就是通过companyId查询出company实体然后在赋值给UserVO中的company属性。

在使用了dozer之后,我们可以把UserDO中的部分属性赋值到UserVO中,其实,转化的过程是通过调用UserDO中的getter方法和UserVO中的setter方法来实现的。读者可以做个实验,对于UserVO中的部分属性不写Setter方法看看还能不能把属性值转换过来,博主已经测试过了,是不能的。


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn