Data Transfer Objects in J2EE Systems

Smaller systems often mock out the business objects in a direct one to one relational mapping to a database table. My little site is a good example; a blog is a well know problem domain and the data objects that are presented to the view do not really differ from the rows in a table. As an example, this is the table I store tags in:

class GoopTag(SQLObject):
    class sqlmeta:
        table='goop_tag'
    garticle = ForeignKey('GoopArticle')
    name = StringCol(length=255,notNone=True)
    tag_order = IntCol(default=0)
    created = DateTimeCol(default=datetime.now

There is no need to create a separate data transfer object (DTO) or value object (VO) to support that structure. However with modern ORMs, including Entity Beans, any relation that comes with a table and is saved in the model, if that is propagated to the view, then all the trailing relationships will come with it. For complex schemas an entire domain model can be dragged up through the system and exposed to the view. This is bad, especially when interacting with third parties.

For larger J2EE systems they are often communicating via remote interfaces and webservices. Presenting the Entity beans as the model through those interfaces means that any changes to the schema will break the outward systems. In a changing business model and a corporate environment of constant change this volatility can be minimized by slapping interfaces over the Entity beans, alternatively, better practice is to create a separate set of value objects that are simple POJOs that do nothing but store data in such a way that it can be transferred across webservice and remote interfaces.

Containers that support distributed systems include service buses. This is intended as the place to orchestrate and aggregate the webservice calls in a Service Oriented Architecture. This is useful when hiding the complexity of calls to multiple systems behind the service bus as one call, but for the majority of calls it tends to be pass through as the calling to one system or another is largely clean and does not require aggregation.

The DTOs that come from the service bus are usually defined in XSD as part of the WSDLs that are being exposed from the service bus. Consequently a J2EE system has many levels of DTOs that need to be exposed, defined and delivered at each level where information passes form one non-contiguous interface to the next.

Getting that level of consistency from one tier and each transfer mechanism to another is important if the system is to be protected from being impervious to change. Once the Entity beans get passed around as concrete objects it rapidly becomes a static system that is heavily coupled from front to back.

Data Transfer Objects, Value Objects and Domain Models in J2EE

Recently I have been dealing with the issue of making sense of different data layers in complex systems. This presentation by Dan Bergh Johnsson helped solidify some of the issues pertaining to data transfer objects, value objects, persistence objects and domain object models. It is very much worth a look. I have summarized it to an extent and put my own examples (Java) in there as I walked myself through it.

Data Transfer Objects (DTO)

Are simple POJOs for the purpose of transporting data around between software sub-system interfaces. The DTOs do not have any behavior other than storage and retrieval of its data.

Purpose is for data transfer.
It is a bunch of data, not necessarily coherent
No behavior

One of the reasons for DTOs in a J2EE system are that Entity beans are not serializable. Another reason is that the domain model and the data being presented to the view is not necessarily the same structures.

Value Objects (VO)

Are domain driven entities that know how to define themselves; they make implicity concepts explicit. Value objects in DDD do validation on the data being passed in. For instance a phone number might be used in a DTO as a String as a VO it will be a PhoneNumber type.

Purpose is for domain representation
High data coherence
Rich behavior

Domain Model (DOM)

Is the relationships between different entities in the system. In J2EE systems these are the Entity Beans that have a one to one mapping with tables in persistent storage. The domain model documents the key concepts and the vocabulary of the system being modeled. This can be applied at many levels; the DTOs, the value objects, the business objects and the persistent objects. In simpler systems often the domain model can do double duty as both the business objects and the persisted entities. In more complex systems these layers need to be broken into different tiers.

Purpose is for domain representation of business concepts

Often in systems domain model for the business objects and the data access layer are one and the same and are defined as Entity Beans or objects in the ORM that directly map to the database schema. In these instances the system has effectively outgrown that architecture and needs two levels added to it; a DTO layer and a Value Object layer.

Database to (Entity Beans) to Stateless Session Beans to (VOs) to Webservices/Remote Interfaces to (DTOs) to other systems such as the view

Data Transfer Object Design

The DTOs are simple storage and do nothing other than transfer data across sub systems. This means they need to match the data requirements of the requesting and receiving systems exactly. For instance the view may request or respond with Credit Card;

public class CreditCardDTO {
     public String cardType;
    public String cardNumber;
    public String ccv;
    public String nameOnCard;
    public String expirationMonth;
    public String expirationYear;
 }

In this instance they are strings as there is no need to describe the data, or do anything complex with the data in a DTO. This would be passed through either the webservices or the remote interfaces to the business logic tier where it would be converted into a value object.

Value Object Design

The VOs are representational of the vocabulary in the domain model and carry the assumptions and behavior inherent in that. Continuing with the Credit Card, when it is changed into a Value Object it will look like:

public class CreditCardVO {
     public CreditCardType creditCardType;
    public CreditCardNumber creditCardNumber;
    public CreditCardCCV creditCardCCV;
    public String nameOnCard;
    public ExpirationDate expirationDate;
 }

The CreditCardVO is composed of other value objects such as the CreditCardNumber. This does validation on the credit card number that is stored in the DTO as a string and then transmits whether it really is a credit card number to the webservice or remote interfaces quickly whether it is or not.

public class CreditCardNumber {
     private String creditCardNumber;
     public CreditCardNumber(CreditCardType type, String creditCardNumber)
        throws ValidationException {
         if (creditCardNumber==null) {
            throw new ValidationException("No credit card number present.");
        }
         if (type==CreditCardType.VISA) {
             if (!Pattern.compile("^4[0-9]{12}(?:[0-9]{3})?$").matcher(this.creditCardNumber).matches()) {
                throw new ValidationException("Not a VISA credit card.");
            }
        }
         this.creditCardNumber = creditCardNumber;
    }
     public String getCreditCardNumber() {
        return this.creditCardNumber;
    }
 }

While this is a bit clunky with a lot of logic present in the constructor that can be refactored it is a good example of dealing with the issue. From this structure a credit card value object knows how to be a credit card number.

Domain Model Design

The business logic tier passes the value objects to the Entities to be transformed into persistent objects in the data store. A credit card value object will be absorbed by a CreditCardProfile Entity Bean and then persisted.

@Entity
public class CreditCardProfile {
     @Id
    private long id;
     @Column
    private String nameOnCard;
     @Column
    private String creditCardNumber;
     @Column
    private Date expirationDate;
 }

At each level of the objects being passed between layers there are different requirements and different vocabularies. Separating the data being moved around the system with DTOs, VOs and Domain Model objects ensures sufficient decoupling that they system is not impervious to future change.

Most Popular on South Sea Republic

The articles that have been viewed the most:

Most Popular Restaurants in Phoenix

Phoenix Eats Out is the restaurant review site for Phoenix, Scottsdale and Old Town Scottsdale which lists the modernist and contemporary restaurants, taverns and bars in the greater Phoenix area. This is the list of the most popular restaurants pages from phoenixeatsout.com that have been viewed the most; My personal favourite restaurants in Phoenix are AZ88, Postinos, Bomberos with Grazie, Humble Pie, Orange Table, The Vig, Fez and others coming close behind. View the complete list with the photo-journalistic style images on phoenixeatsout.com

Most Popular Hikes in Arizona

Arizona is an outdoor state and has lots of hiking in the city and around the state. Phoenix is unusual for most cities in having several large mountains in the center of the city with great hiking. Anyone who comes to Phoenix has to do the Echo Canyon trail on Camelback and the Summit Hike on Squaw Peak or Piesta Peak. The views of the city, suburbs and surrounding mountains are wonderful from Camelback and Piesta Peak. For more experienced hikers there is the McDowell Mountains in North Scottsdale that has several difficult and strenuous hikes in Tom's Thumb and Bell Pass. Alternatively, you can hike the highest mountain in Arizona. At 12,600 feet Humphrey's Peak is a long and difficult hike.

Alternate Australian Constitutions

Between 2004 and 2009 this site, southsearepublic.org, was a constitutional blog based on scoop which focused on Australian and global constitutional issues. One of the strongest aspects of it was the development of constitutions by those involved in the blog. These constitutions are the outcome: The constitutions were built using principles from Montesquieu's separation of powers, the enlightnment's universal political rights and the ancient Athenian technology of sortition and choice by lot.

Archives For South Sea Republic

South Sea Republic started in 2004 as an Australian constitutional blog in 2004 based on scoop software. It was an immigrative outgrowth of Kuro5hin. The archives for each year since then; The articles are ordered by views.

Who Is Cam Riley

Cam Riley I am an Australian living in the United States as a permanent resident. I am a software developer by trade and mostly work in Java and jump between middleware and front end. I originally worked in the New York area of the United States in telecommunications before moving to Washington DC and working in a mix of telecommunications, energy and ITS. I started my own software company before heading out to Arizona and working with Shutterfly. Since then I have joined a startup in the Phoenix area and am thoroughly enjoying myself.

I do a lot of photography which I post on this website, but also on flickr. I have a photo-journalistic website which lists the modernist and contemporary restaurants in phoenix. I have a site on the Australian Flying Corps [AFC] which has been around since the 1990s and which I unfortunately lost the .org URL to during a life event; however, it is under the www.australianflyingcorps.com URL now. The AFC website has gone through several iterations since the 90s and the two most recent are Australian Flying Corps Archives(2004-2002) and Australian Flying Corps Archives(2002-1999) which are good places to start.

Websites Worth Reading

Websites of friends, colleagues and of interest;