Java Code Geeks

Friday, December 26, 2008

DAO layer in J2EE Apps

Phew.... its been a crazy time. There was a product release and things were pretty hectic. Hence did not get time to write anything on the post. Now that the Chrismas vacation is here, need to spend time with family also :-)

Anyway, I thought of writing this post on Data Access Layer of J2EE. How many times we write DAO layers yet we dont get it right at the first time. I was reviewing some of the codes and found out that people do not understand why they are writing a DAO and just write it cause its mentioned somewhere that it is a good practice.

okay, so as we all know that we introduce DAO layer to abstract the data access layer. For example, if your application runs on MySQL, SQL Server, Sybase and Oracle, the DAO developer makes sure that he introduces a nice abstraction layer which hides all of these database related differences. The client code of DAO - which is many times the Session Facade or Value List Handers, do not have to worry about loading the JDBC driver and creating DB specific SQLs.
Doing so, DAO layer needs to make sure that it opens a connection with database, prepare statement object, create resultset , retrieve data and close the connection and resultset. Closing the connection and resultset are important otherwise you will have leaked cursors at the database layer. It is also important to make sure DAO layer catches all the JDBC/SQL specific exceptions and convert them to application specific exceptions. Lot of DAO developers do not handle the exceptions from the DAO layer which defets the purpose of having another layer. The idea is that any code which is going to use the DAO, should not have to use java.sql.* or javax.sql.* packages at all.
There are many ways to create a DAO layer, if we refer to the Suns J2EE blueprint site -
http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html

No comments: