Monday, January 20, 2014

How to implement Data Transfer Object design pattern in J2EE

In this post I am going to talk about DTO design patterns.

Clients of enterprise J2EE applications need to pass and retrieve data from the service object or business object.

Multiple calls for the Web Service, Enterprise bean, or Business object causes network overhead. Knowing that clients could require the data from business tier for reading, display, and other operations over the network.

To give a solution for these network-degrading through multiple read/write operations we use Data Transfer Object to encapsulate the needed data represented by a Transfer Object.

Transfer Objects encapsulates all the fields needed by the client to read or write from the enterprise application.

Clients could require more than one value from the web service or the enterprise bean. So, it is better to allow the client to make a single method call and passing a transfer object that encapsulates all the required data to the business tier and enable him from reading the needed data as a Transfer Object Response that encapsulates the required values.

The following figure showing the data flow between client and business tier; the user sends a Transfer Object Request to the business tier, and the business tier response back with a Transfer Object Response to the client.
  

DTO Example

The following snippet of code shows a sample implementation for Data Transfer Object. The Web Service remote interface allow user to enter his/her data and populate a Data Transfer Object and pass it to the web service to process client’s request.

The web service responds to the user request with a Response Transfer Object that encapsulates the requested data.




From the above code snippet, note the usage of Data Transfer Object. We have created two Transfer Objects, one for Request, and one for Response.

Note that these transfer objects contains the required data that the client may need. For example class GetEmployeeInfoResponseDTO contains the following fields regarding the requested employee.





The request DTO is handled the same way, you create a class that contains the necessary fields that the client need to pass for the business tier for processing, and the business tier responds with another Response transfer object.