Thursday, 22 December 2011

Hitting the Database with Spring 3.x




Basic Idea:

The Term DAO stands for Data Access Objects. DAOs do basic function of interacting with the database.
They contain database read/write logic and expose their functionality to the rest of the application via interfaces as shown in the figure below.



The philosophy of coding to interfaces has a couple of things to note..
  1. Your service layer that invokes DAO is testable now as you can provide a mock implementation of your DAOs Interface without event connecting to the database.
  2. Your service layer accesses the database in a database-agnostic manner. It does not need to know what database is being invoked by the DAO class. All it cares about is the interface methods.
One way spring helps you separate your data access tier from rest of your application is by providing a consistent Exception hierarchy that's used across all of it's DAO frameworks.

Spring's data access Exception hierarchy

 Plain vanilla JDBC forces you to handle SQLException. SQLException means that something went wrong while you were trying to access the database. It is tell what went wrong and how to handle it. Some common reasons of SQLException being thrown are
  • Application is not able to connect to the database.
  • Query being executed has syntax errors.
  • Table/Columns referred-to in the query doesn't exist.
  • An attempt to insert/Update values in database that violate a database constraint.
Most of the times when a SQLException is thrown, nothing much can be done to remedy it in a catch block. Most SQLExceptions represent FATAL conditions like application not being able to connect to the database. A query having a syntax error etc.. not much can be done to fix them on runtime.

1 comment: