简体   繁体   English

Java中的DTO(数据传输对象)和类对象之间的区别?

[英]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. 主要区别在于DTO在设计上没有任何业务逻辑。 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. 例如:您可能拥有一个存储“用户”的数据库,如果使用DTO,您可以使用UserBean来存储和检索用户对象。 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. 但是您的业务逻辑可能有一个User对象(可能来自bean,更可能是通过聚合使用bean),它不仅具有数据,而且还有User可以执行的其他方法。

I believe this should be true: 我相信这应该是真的:

assertTrue(POJO == DTO)

The only special thing about DTO is that they should not contain any behavior. 关于DTO的唯一特殊之处在于它们不应包含任何行为。

1, The class object maybe contains too many references to other objects, thus too big to be serialized to transfer. 1,类对象可能包含太多对其他对象的引用,因此太大而无法序列化传输。 DTO only selects the interesting parts, this can be a performance gain. DTO只选择有趣的部分,这可以提高性能。

2, In Hibernate, the entity object may contain lazy-initialized references, these objects need session context to do initialization. 2,在Hibernate中,实体对象可能包含延迟初始化的引用,这些对象需要会话上下文来进行初始化。 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. 这些实体对象看起来像“智能对象”,DTO在这里将这些“智能对象”转换为“普通对象”,因为当会话上下文不再存在时,传输“智能对象”是没有意义的。

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. 就个人而言,我不喜欢DTO,它引入了另一层冗余,但有时候(特别是在使用Hibernate ORM时)我不能没有它。

A DTO class is an ordinary Java class with a just special meaning - just like a Observer , a Factory or a Model . DTO类是一个普通的Java类,具有特殊含义 - 就像ObserverFactoryModel一样 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. 该名称来自核心J2EE设计模式( 传输对象模式),该模式提出了一种在数据库和基于java类的模型之间传递信息的通用方法。

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. 简而言之,DTO是一个java类,其中类名映射到数据库表名,每个数据库列映射到class属性。 Then it contains getter and setter methods. 然后它包含getter和setter方法。

Here is one explanation of the (Data) Transfer Object pattern . 以下是(数据)传输对象模式的一种解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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