Difference between DTO(data transfer object ) and class object in java? - 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.

Related

Is the JSF Bean different from the standard Bean? [duplicate]

Have seen some similar questions:
What is the difference between a JavaBean and a POJO?
What is the Difference Between POJO (Plain Old Java Object) and DTO (Data Transfer Object)?
Can you also please tell me the contexts in which they are used? Or the purpose of them?
JavaBeans
A JavaBean is a class that follows the JavaBeans conventions as defined by Sun. Wikipedia has a pretty good summary of what JavaBeans are:
JavaBeans are reusable software components for Java that can be manipulated visually in a builder tool. Practically, they are classes written in the Java programming language conforming to a particular convention. They are used to encapsulate many objects into a single object (the bean), so that they can be passed around as a single bean object instead of as multiple individual objects. A JavaBean is a Java Object that is serializable, has a nullary constructor, and allows access to properties using getter and setter methods.
In order to function as a JavaBean class, an object class must obey certain conventions about method naming, construction, and behavior. These conventions make it possible to have tools that can use, reuse, replace, and connect JavaBeans.
The required conventions are:
The class must have a public default constructor. This allows easy instantiation within editing and activation frameworks.
The class properties must be accessible using get, set, and other methods (so-called accessor methods and mutator methods), following a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties.
The class should be serializable. This allows applications and frameworks to reliably save, store, and restore the bean's state in a fashion that is independent of the VM and platform.
Because these requirements are largely expressed as conventions rather than by implementing interfaces, some developers view JavaBeans as Plain Old Java Objects that follow specific naming conventions.
POJO
A Plain Old Java Object or POJO is a term initially introduced to designate a simple lightweight Java object, not implementing any javax.ejb interface, as opposed to heavyweight EJB 2.x (especially Entity Beans, Stateless Session Beans are not that bad IMO). Today, the term is used for any simple object with no extra stuff. Again, Wikipedia does a good job at defining POJO:
POJO is an acronym for Plain Old Java
Object. The name is used to emphasize
that the object in question is an
ordinary Java Object, not a special
object, and in particular not an
Enterprise JavaBean (especially before
EJB 3). The term was coined by Martin
Fowler, Rebecca Parsons and Josh
MacKenzie in September 2000:
"We wondered why people were so against using regular objects in their
systems and concluded that it was
because simple objects lacked a fancy
name. So we gave them one, and it's
caught on very nicely."
The term continues the pattern of
older terms for technologies that do
not use fancy new features, such as
POTS (Plain Old Telephone Service) in
telephony, and PODS (Plain Old Data
Structures) that are defined in C++
but use only C language features, and
POD (Plain Old Documentation) in Perl.
The term has most likely gained
widespread acceptance because of the
need for a common and easily
understood term that contrasts with
complicated object frameworks. A
JavaBean is a POJO that is
serializable, has a no-argument
constructor, and allows access to
properties using getter and setter
methods. An Enterprise JavaBean is not
a single class but an entire component
model (again, EJB 3 reduces the
complexity of Enterprise JavaBeans).
As designs using POJOs have become
more commonly-used, systems have
arisen that give POJOs some of the
functionality used in frameworks and
more choice about which areas of
functionality are actually needed.
Hibernate and Spring are examples.
Value Object
A Value Object or VO is an object such as java.lang.Integer that hold values (hence value objects). For a more formal definition, I often refer to Martin Fowler's description of Value Object:
In Patterns of Enterprise Application Architecture I described Value Object as a small object such as a Money or date range object. Their key property is that they follow value semantics rather than reference semantics.
You can usually tell them because their notion of equality isn't based on identity, instead two value objects are equal if all their fields are equal. Although all fields are equal, you don't need to compare all fields if a subset is unique - for example currency codes for currency objects are enough to test equality.
A general heuristic is that value objects should be entirely immutable. If you want to change a value object you should replace the object with a new one and not be allowed to update the values of the value object itself - updatable value objects lead to aliasing problems.
Early J2EE literature used the term value object to describe a different notion, what I call a Data Transfer Object. They have since changed their usage and use the term Transfer Object instead.
You can find some more good material on value objects on the wiki and by Dirk Riehle.
Data Transfer Object
Data Transfer Object or DTO is a (anti) pattern introduced with EJB. Instead of performing many remote calls on EJBs, the idea was to encapsulate data in a value object that could be transfered over the network: a Data Transfer Object. Wikipedia has a decent definition of Data Transfer Object:
Data transfer object (DTO), formerly known as value objects or VO, is a design pattern used to transfer data between software application subsystems. DTOs are often used in conjunction with data access objects to retrieve data from a database.
The difference between data transfer objects and business objects or data access objects is that a DTO does not have any behaviour except for storage and retrieval of its own data (accessors and mutators).
In a traditional EJB architecture, DTOs serve dual purposes: first, they work around the problem that entity beans are not serializable; second, they implicitly define an assembly phase where all data to be used by the view is fetched and marshalled into the DTOs before returning control to the presentation tier.
So, for many people, DTOs and VOs are the same thing (but Fowler uses VOs to mean something else as we saw). Most of time, they follow the JavaBeans conventions and are thus JavaBeans too. And all are POJOs.
DTO vs VO
DTO - Data transfer objects are just data containers which are used to transport data between layers and tiers.
It mainly contains attributes. You can even use public attributes without getters and setters.
Data transfer objects do not contain any business logic.
Analogy: Simple Registration form with attributes username,
password and email id.
When this form is submitted in RegistrationServlet file you will get all the attributes from view layer to business layer where you pass
the attributes to java beans and then to the DAO or the persistence layer.
DTO's helps in transporting the attributes from view layer to business layer and finally to the persistence layer.
DTO was mainly used to get data transported across the network efficiently, it may be even from JVM to another JVM.
DTOs are often java.io.Serializable - in order to transfer data across JVM.
VO - A Value Object [1][2] represents itself a fixed set of data and is similar to a Java enum. A Value Object's identity is based on their state rather than on their object identity and is immutable. A real world example would be Color.RED, Color.BLUE, SEX.FEMALE etc.
POJO vs JavaBeans
[1]
The Java-Beanness of a POJO is that its private attributes are all accessed via public getters and setters that conform to the JavaBeans conventions. e.g.
private String foo;
public String getFoo(){...}
public void setFoo(String foo){...};
[2]
JavaBeans must implement Serializable and have a no-argument constructor, whereas in POJO does not have these restrictions.
Basically,
DTO: "Data transfer objects " can travel between seperate layers in software architecture.
VO: "Value objects " hold a object such as Integer,Money etc.
POJO: Plain Old Java Object which is not a special object.
Java Beans: requires a Java Class to be serializable, have a no-arg constructor and a getter and setter for each field
Java Beans are not the same thing as EJBs.
The JavaBeans specification in Java 1.0 was Sun's attempt to allow Java objects to be manipulated in an IDE that looked like VB. There were rules laid down for objects that qualified as "Java Beans":
Default constructor
Getters and setters for private data members that followed the proper naming convention
Serializable
Maybe others that I'm forgetting.
EJBs came later. They combine distributed components and a transactional model, running in a container that manages threads, pooling, life cycle, and provides services. They are a far cry from Java Beans.
DTOs came about in the Java context because people found out that the EJB 1.0 spec was too "chatty" with the database. Rather than make a roundtrip for every data element, people would package them into Java Beans in bulk and ship them around.
POJOs were a reaction against EJBs.
POJO :
It is a java file(class) which doesn't extend or implement any other java file(class).
Bean:
It is a java file(class) in which all variables are private, methods are public and appropriate getters and setters are used for accessing variables.
Normal class:
It is a java file(class) which may consist of public/private/default/protected variables and which may or may not extend or implement another java file(class).
Value Object : Use when need to measure the objects' equality based on the objects' value.
Data Transfer Object : Pass data with multiple attributes in one shot from client to server across layer, to avoid multiple calls to remote server.
Plain Old Java Object : It's like simple class which properties, public no-arg constructor. As we declare for JPA entity.
difference-between-value-object-pattern-and-data-transfer-pattern
First Talk About
Normal Class - that's mean any class define that's a normally in java it's means you create different type of method properties etc.
Bean - Bean is nothing it's only a object of that particular class using this bean you can access your java class same as object..
and after that talk about last one POJO
POJO - POJO is that class which have no any services it's have only a default constructor and private property and those property for setting a value corresponding setter and getter methods.
It's short form of Plain Java Object.

Code example POJO and DTO

I don't understand the difference between POJO and DTO in Java. I have read the article here: What is the Difference Between POJO (Plain Old Java Object) and DTO (Data Transfer Object)? . But I still don't understand the code implementation between them, what makes them different. Can you give the code example for each of them? Thank you so much before!
POJO means Plain Old Java Object. A POJO is an object that doesn't need to implement any specific interface or extend some specific class to be used by a framework. The term has been coined, if I remember correctly, to react against EJB1 and EJB2 which imposed a lot of constraints on the way you had to write beans to make them EJBs. POJO is more a marketing term than a technical term.
DTO means Data Transfer Object. A DTO is an object that is used to transfer data between layers of an application, typically over the network. It often consists in a POJO (i.e. a simple Java class) containing fields and getters.
A Plain Old Java Object or POJO is a term initially introduced to designate a simple lightweight Java object,
not implementing any javax.ejb interface in contrast to Entity beans
Now a days , POJO term is used for any simple object with no extra fancy annotation like third party annotations etc
DTO is an object whose responsibility is just to encapsulate data in a value object . It will just have instance members and corresponding getters and setters. Generally they used to represent the row in data store. While pojo include some more methods that doing some business processing on them
Actually, POJO is more general. Any class which has private serializable fields, getters and setter for each field and doesnt extend other class or implement an interface may be called POJO.
DTO is an object which uses some data object (for example, JPA entity object) to transfer data to another tier of your application (for example, if entity1 object has reference to other entity2, DTO can replace entity2 reference by its entity2.id.toString or other entity2 field).

Difference between business object and transfer object?

While many stackoverflow answers regarding this question exists, rarely do they clearly distinguish the difference between the two. As a result, I am having confusion in understanding them.
Here I am working with this pattern
Referring to the figure 9.1, both business object and transfer object are used. While definition of both are given along the lines as:
generally considered to be a class that represents an Entity, e.g. a Book or a Store. Such a class has certain properties like price, colour, width, isbn number etc. In Java or .NET, it consists of so-called setters and getters
Now DTOs have same definition. It appears to me like a Bean representing an object. So in a standalone application what could possibly be business object and DTO. Please distinguish between the two in terms of the pattern link above.
A DTO is used to transport the data from one layer to other, (for example from the data access layer to the model).
A BO contains the Business Logic.
But the most important thing in this patterns is to separate the layer, in order to make the software more easily maintained.
For example, if you separate the data access layer, it doesn't matter if you are using a database to get the data, or a socket, or a plain text file separated with pipelines, you can change this and it will not affect the rest of the layers.
That article defines:
The BusinessObject represents the data client. It is the object that requires access to the data source to obtain and store data. A BusinessObject may be implemented as a session bean, entity bean, or some other Java object, in addition to a servlet or helper bean that accesses the data source.
and
This represents a Transfer Object used as a data carrier. The DataAccessObject may use a Transfer Object to return data to the client. The DataAccessObject may also receive the data from the client in a Transfer Object to update the data in the data source.
Surely you can see the difference between a class that wants to obtain and store data in a data source, and an object that simply carries data between layers?

Are Jackson mapped objects DAOs?

I'm using Jackson to map JSON to a Java object.
Is the created Java object a DAO since its an object representation of the JSON structure and so is providing access to the JSON data?
It is not a DAO design pattern.
DAO pattern stands for providing the access to the Data Layer.
I will rather say it Value Object.
No, i would say its a data transfer object.
DAOs are used to persist data.
Since you are mapping from one instance to another instance, I think you are using more of a Converter or Adapter (take a look at the adapter pattern here).
To my knowledge, the purpose of the DAO (Data Access Object) is to provide a layer, or an object, which provides some sort of access to your data storage.
It is a Memento, for "Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later" I wouldn't argue with calling it Value Object but it's definitly not a DAO which the defining characteristic is the abstraction of a persistent data story.

Best Practice: String converting batch in instantiating class or capsulated in every instantiated class

One class Customers instantiates many other classes (e.g. CustomersFromMysql, CustomersFromPostgeSQL) that all query databases which give back customer names. Now these customer names come back as for example name = "John Doe", what my Customers class needs though is more than name, it also needs nameNoSpace = "JohnDoe" and nameInvertedComma = "Doe, John" for example.
I would programm a helper class Converter which has methods like invertName(name) and removeComma(name). Would I instantiate the converter in every class that queries the database (CustomersFromMysql, CustomersFromPostgeSQL) to give back all required variables or would I instantiate the Converter in the instantiating class Customers so when I get back results I iterate through my list and batch convert them?
Of course both works, but what is the way to go?
You should remember separation of duties in such cases. The database related classes should handle only the database specific aspects. Performing operations (calculations) on the retrieved data should be treated as business logic. So, if your Customers class already has some logic in it, it would be the perfect place for putting in the conversion routines. Neverthess, it really depends on where you think your logic belongs to.
It may also make sense to apply some naming conventions. In general you can distinguish between at least the different kinds of classes in case like the one you desribed in your question:
Data Access Objects (DAO); perform database opertions (your SQL classes)
Data Transfer Objects (DTO) or entities; represent the structure of your business objects
Business Logic; retrieve the DTO by using DAOs, perform some logic according to your requirements, push the DTO back into the database by using the DAOs again

Categories