Tuesday, February 06, 2007

JDBC convenient programming with Spring

There is no need to re-iterate what has already been said and spread about the usefulness of the Spring framework... but it seems that every time I make use of a feature I come to the same conclusion: it simply makes you more satisfactory of your code, that is how I see it anyway !

Most of my database-related code usually made use of Hibernate because the sizing and the extend of the domain model simply justified leveraging the complexity of this framework.

However, in my current project I decided to give a shot at Spring jdbc support packages mostly because my domain model is simple enough (less than 10 entities with basic relationship) and because... well exploring more of the Spring library!


Although the library only really offers some thin wrapper around jdbc api (as opposed to a complete ORM solution), it does it in a way that you can create your data access code in a more object oriented fashion while keeping a close access to the underlying jdbc low-level api.

To illustrate this, I've created some helper classes (one per each business object entity) wrapping Spring jdbc data access object (e.g. SQLUpdate, JdbcTemplate, MappingSqlQuery) and offering a convenient way to centralize all sql-related string (sql command, table name and field, etc..).

On top of these classes, you can actually implement all generic sql access code (e.g. delete by id) and generic sql commands. Here's how look like the superclass, refer here as BaseSqlHelper:


And Here's one example of how one could implement a particular subclass (in this specific example the subclass handles sql for the User business entity object):



What does this offer you:
1- get all your sql strings contralized in one convenient place
2- benefit from code re-use by moving-up all your common fields (e.g. id, createDate,..) and common sql operations (e.g. delete from ... where id=, select ... from ... where id=) for all business entities into the superclass
3- exploit the MapRow capability to treat query response as real business entities and not merely as data field.
4- Ease for accomodating new fields and remove existing ones


Martin