国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home 類庫下載 java類庫 Use Dozer to elegantly convert DO to VO

Use Dozer to elegantly convert DO to VO

Oct 15, 2016 pm 01:42 PM

What are DO, DTO and VO

Various model concepts in Java have been introduced in the concepts of VO, PO, DO, DTO, BO, QO, DAO and POJO in Java.
Here is a brief summary:

In daily project development, VO corresponds to the data (form) that needs to be displayed on the page, DO corresponds to the data stored in the database (data table), and DTO corresponds to the other than the two. Data that needs to be transferred externally.

Many people may not be so familiar with VO and DTO, but are more familiar with DO. That is because in many projects we only use DO for various reasons. The reasons may be as follows:

1. The project is too Small, for a business entity, it is enough to encapsulate it into a DO.

2. I am not familiar with DTO and VO, let alone the difference between them.

3. I know the difference between DODTOVO, but I am too lazy to use it.

So, here, the blogger will explain why so many concepts are introduced, and why I recommend that you use these entity objects in your projects.

Why can’t we just use one DO

Let’s look at such an example. Suppose there is an entity like User in our project. When we create the User table, we generally include the following attributes:

Use Dozer to elegantly convert DO to VO

For this entity, we usually need to create a DO class to encapsulate this User entity.

public class UserDO {
    private Integer id;                 //唯一主鍵
    private Date createdTime;           //創(chuàng)建時間
    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;             //數(shù)據(jù)狀態(tài),1表示可用,0表示不可用
 
    //setter and getter
}

Then, in the code, from DAO to front-end display, we transmit data through the object of this UserDO class. Are there any problems with doing this?

Unnecessary fields are also passed to the front-end page.

For fields such as password, createdTime, updatedTime and status, we may not need to display them on the front end at all, but these fields may also be passed to the front end (unless we do not query the corresponding fields during SQL query). This not only increases the amount of data transmission, but may also cause security issues.

Some fields need to be converted, but cannot be supported.

For the political appearance field in the above example, we store numbers in the database, but what I want to display on the front-end page is a Chinese description. This situation can only be displayed on a case-by-case basis through if/else on the front end.

Some fields want to be displayed, but they do not want to appear in the database

In the User table, we only save the companyId of this user, and we need to query the company table at the same time to find out more detailed information about the company. For the User object, what if we want to display the company he belongs to at the same time on the front end and want to find out all of them through one query? There are several simple solutions. The first one is to let UserDO contain an attribute of the Company class and pass it through this attribute. Another option is to write the Company attributes we want to pass to the front end into UserDO. However, if this is really done, can UserDO still be called DO?

There are still many questions, so I won’t go into details here.

It can be seen that using one DO from beginning to end (from database to front-end page) is not a good design.

How to use DO, DTO, VO correctly

For the above example, we can design it into the following class. Since the model is not complicated, we only need to introduce VO here.

UserDO already corresponds to the database field one-to-one, no modification is needed here.

public class UserDO {
    private Integer id;                 //唯一主鍵
    private Date createdTime;           //創(chuàng)建時間
    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;           //學(xué)歷
    private String politicalStatus;     //政治面貌,1表示群眾,2表示團員,3表示黨員,4表示其他,100表示未知
    private Integer companyId;          //公司的ID
    private Integer status;             //數(shù)據(jù)狀態(tài),1表示可用,0表示不可用
 
    //setter and getter
}

Introduces UserVO to encapsulate the fields that need to be displayed on the front end.

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;           //學(xué)歷
    private String politicalStatus;     //政治面貌,群眾、團員、黨員等
    private Company company;            //公司
 
    //setter and getter
}

UserVO only contains the fields required for display, and fields that are not required for display do not need to be included here.

After introducing this class, we can use UserDO when performing database queries, and then convert DO to VO when it needs to be passed to the front end.

Summary

Seeing this, you may have discovered that UserDO and UserVO contain a large number of the same fields. Is it really necessary to design a separate VO? What I can tell you clearly is that when your system becomes larger and larger and there are more and more fields in the table, it is absolutely beneficial to use concepts such as DODTOVO for hierarchical processing. As for how to effectively convert between different entity classes, I will introduce it next.

Elegantly convert DO to VO

Dozer is an object conversion tool.

Dozer可以在JavaBean到JavaBean之間進行遞歸數(shù)據(jù)復(fù)制,并且這些JavaBean可以是不同的復(fù)雜的類型。
所有的mapping,Dozer將會很直接的將名稱相同的fields進行復(fù)制,如果field名不同,或者有特別的對應(yīng)要求,則可以在xml中進行定義。

前面我們介紹的DO\DTO\VO不就是JavaBean嘛。正好可以使用Dozer進行轉(zhuǎn)換呀。
除了使用Dozer,當然你還由其他選擇:

典型的解決方案就是手動拷貝,弊端很明顯,代碼中充斥大量Set 和Get方法,真正的業(yè)務(wù)被埋藏值與值的拷貝之中。

另一種方案就是使用BeanUtil,但BeanUtil不夠很好的靈活性,又時候還不得不手動拷貝。Dozer可以靈活的對對象進行轉(zhuǎn)換,且使用簡單。

Dozer 支持的轉(zhuǎn)換類型

Primitive 基本數(shù)據(jù)類型 , 后面帶 Wrapper 是包裝類 Complex Type 是復(fù)雜類型

?   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 到復(fù)雜類型 , 如果復(fù)雜類型包含一個 String 類型的構(gòu)造器 
?   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進行類轉(zhuǎn)換

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);
    }
}

特殊的字段轉(zhuǎn)換
在使用mapper進行轉(zhuǎn)換前,設(shè)置一個或多個mapping文件

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

配置dozer-mapping.xml文件

數(shù)據(jù)類型不一致,或者名稱不相同或者有級聯(lián)關(guān)系等情況下,可以通過文件dozer-mapping.xml來進行定制Bean的轉(zhuǎn)換

<?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的轉(zhuǎn)換

@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;
}

通過以上的代碼加配置,我們就實現(xiàn)了從DO轉(zhuǎn)換到VO的部分操作,之所以說是部分操作,是因為我們在dozer-mapping.xml并沒有做多余的配置,只是使用dozer將DO中和VO中共有的屬性轉(zhuǎn)換了過來。對于其他的類型不同或者名稱不同等的轉(zhuǎn)換可以參考官網(wǎng)例子通過設(shè)置dozer-mapping.xml文件來實現(xiàn)。

上面還有一個getCompany()沒有實現(xiàn)。這個方法其實就是通過companyId查詢出company實體然后在賦值給UserVO中的company屬性。

在使用了dozer之后,我們可以把UserDO中的部分屬性賦值到UserVO中,其實,轉(zhuǎn)化的過程是通過調(diào)用UserDO中的getter方法和UserVO中的setter方法來實現(xiàn)的。讀者可以做個實驗,對于UserVO中的部分屬性不寫Setter方法看看還能不能把屬性值轉(zhuǎn)換過來,博主已經(jīng)測試過了,是不能的。


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72