Java Vibes..

August 19, 2009

Hibernate Quick References…

Filed under: java frameworks — harjitdelhi @ 11:41 am
Tags: , , ,

Here are some common tips that every hibernate developer must know. Will post detailed examples later, just posting a few quick links right now for ready reference:


June 30, 2009

Template Pattern and Spring

Filed under: architecture & design — harjitdelhi @ 1:09 pm
Tags: , , , , ,

As you might be aware, Template is a GoF behavioral pattern. Here I first explain what the Template pattern is and then show an example of the pattern as implemented in the Spring framework:

Template works on the philosophy of Abstract classes, wherein the Abstract class implements some boiler plate functionality and let the subclasses implement the specifics.

For example, when you want to execute a JDBC query against a database, you have to implement the following steps:

  1. Obtain a DataSource
  2. Use the DataSource to get a Connection object
  3. Use the Connection object to create a Statement (or a PreparedStatement)
  4. Execute a query to get the ResultSet
  5. Iterate over the results and create a list of VOs (as an example of a business logic)
  6. Close the ResultSet
  7. Close the Statement
  8. Close the Connection

Out of the above steps, most of these are boiler plate code while steps #4 and #5 reflects the actual business logic. If you create a Template class (essentially an Abstract class) that models these steps and allow subclasses to customize the steps #4 and #5 then it will help subclasses reuse the boiler plate code.

Spring does this by providing classes like JdbcTemplate, HibernateTemplate, JmsTemplate etc.  Here is how things work in the Spring world:


Example code:
List results = getHibernateTemplate().executeFind(new HibernateCallback() {
                   public Object doInHibernate(Session session) {
                       Query query = session.createQuery("from Event");
                       return query.list();

Blog at