简体   繁体   中英

Difference between DTO(data transfer object ) and class object in java?

We can use a class object for transfering data to another class. what is the speciality of data transfer objects? How to create them ? Is it just like class objects?

The primary difference is that DTOs, by design, don't have any business logic in them. They're just data structures.

For instance: You might have a database in which you store "users", and if using DTOs, you might use a UserBean to store and retrieve user objects. But your business logic may have a User object (possibly derived from the bean, more likely using the bean via aggregation) that not only has the data, but additional methods for things that User can do.

I believe this should be true:

assertTrue(POJO == DTO)

The only special thing about DTO is that they should not contain any behavior.

1, The class object maybe contains too many references to other objects, thus too big to be serialized to transfer. DTO only selects the interesting parts, this can be a performance gain.

2, In Hibernate, the entity object may contain lazy-initialized references, these objects need session context to do initialization. These entity objects looks like "smart objects", DTO here convert these "smart objects" to "plain objects", because transfer "smart objects" is meaningless when the session context is no more existed.

Personally, I don't like DTO, it introduce another layer of redundant, but sometime (especially when working with Hibernate ORM) I can't live without it.

A DTO class is an ordinary Java class with a just special meaning - just like a Observer , a Factory or a Model . The name is coming from a core J2EE design pattern (the Transfer Object pattern) and the pattern proposes a common way to transfer information between a database and java-classes-based model.

In brief, a DTO is a java class where the class name maps to a database table name and each database column maps to a class attribute. Then it contains getter and setter methods.

Here is one explanation of the (Data) Transfer Object pattern .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM