Monday, January 20, 2014

How to implement Data Access Object design pattern in J2EE

In this post I am going to talk about design patterns, specifically, Data Access Object (DAO).
Many J2EE applications needs or must connect to a backend data source. Some data sources may be different in type and location; some systems need to access LDAP repositories; data resides in an external mainframe, and so forth.

J2EE applications can use JDBC API to access data in Relational Database Management System (RDBMS). As you know, JDBC API enables J2EE applications from accessing database data in a standard way, regardless of the vendor.

DAO encapsulates all the access to a given data source by managing the connection to a data source, that enables you from accessing RDBMS.Please refer to create data source post

The DAO encapsulates the access required to work with the data source. The data source could be any persistent store like an RDBMS, an external service (B2B exchange), a repository like an LDAP database, etc.

The strength and forces to use DAO design pattern is to completely hide the data source implementation details from its clients. This will allow you to hide the data source connection details from outside client and allows the DAO to adapt to different storage schemes without affecting its clients or business components.
That is mean; the DAO acts as an adapter between the component and the data source.

J2EE DAO Example
The following snippet of code illustrates the usage of DAO design pattern, and shows how to utilize JDBC to connect to a data source that refers to Oracle database.
The client interacts with a web service, which in turn, interacts with a Data Access Object that’s encapsulating data source details from outside world.


1.       From the above figures, we can structure of the application; a client requests a service from a web application.
2.       The service uses DAO to access the database and get the required info.
3.       DAO encapsulates the data store connection details.

The above diagram is implemented as following:
1.       Create a web service that expose some services to outside world.
2.       Create a DAO class that encapsulates the connection details for RDBMS.

The following snippet of code illustrates the implementation of DAO class that encapsulates the connection to database details.

Note that your data source must be configured at application server; you can refer to How to create datasource post.



After that you need to implement your web service, and from within a web method you can instantiate your DAO class, and call the desired method.
  



I am going to illustrate the whole program after I complete posting for each part alone, in next post I will talk about other kind of J2EE design patterns, DTO (Data Transfer Object).