01 February 2009

Data Access Object (DAO), a J2EE Design pattern

DAO is a famous J2EE Design pattern, really it provides many services to your design as it brings more flexibility to your system, but also brings complexity.

It's the story; the more flexible is your system, the more complicated it is.

Let's discuss briefly the DAO design pattern and its associated patterns:





The class pattern is shown as CustomerDAO
CustomerBO implements Business Object J2EE pattern
Customer implements ValueObject (Data Transfer Object ) J2EE pattern

As shown, the DAO pattern isolate between the Buisness layer ( Customer BO ) and the underlying implementation of the Datasource.
The Buisness layer calls the DAO objects that depend on the underlying datasource, so the only portion of code we need to change when changing the datasource implementation mechanism (useing ORM instead of JDBC , or uses OODBMS instead of RDBMS )

Basic DAO implementation:

public class CustomerDAO extends AbstractDAO {

Customer customer;
DBCommon dbManager;

public CustomerDAO(Customer customer, DBCommon dbManager)throws DBException {
this();
this.customer = customer;
this.dbManager = dbManager;
}

public CustomerDAO(Customer customer)throws DBException {
this();
this.customer = customer;
}

public CustomerDAO(DBCommon dbManager)throws DBException {
this();
this.dbManager = dbManager;
}
public void delete() throws DBException {

boolean result = false;

try {
result = dbManager.deleteRecord("Customers", " cust_id = " + customer.getId());

}catch (DBException e) {
e.printStackTrace();
throw new ObjectNotDeletedException("cannot delete customer");
}finally {
dbManager.close();
}

if ( !result )
throw new ObjectNotDeletedException("cannot delete customer");
}
public Customer load(long identityKey) throws DBException {
//
}

//reset of CRUD methods
}

From the preceding sample we get that DAO objects in its simplest form is an object that implement basic CRUD (Create – Read- Update- Delete ) operations in its simplest fom.

There are more sophisticated techniques to create DAO objects using GoF patterns (Factory method and Abstract Factory patterns) (refer to Core J2EE Patterns : Best practice and Design strategies by Deepak Alur et. al. )

Value Objects
These are basic POJOs ( javabeans object ) used to transfer data between layers, between the application layer and the business layer for example.

This pattern uses along with DAO pattern to transfer data between the DAO layer ( data access layer or integration layer) and Business layer

Business Objects
Is the objects that depends on DAO objects to execute Business functions of the system.

2 comments:

alaa said...

is that pattern=MVC ??

mhewedy said...

Welcome brother Alaa @ my blog,

No, that is not the MVC, this pattern resides in the Persistence tier.