I've previously written a small del.icio.us clone using Hibernate where some of the code was generated using Middlegen. I like the Hibernate approach but it sometimes feels like a heavyweight approach for a simple application (e.g. sledgehammer to crack a walnut).

I have looked at using Spring and the JDBCTemplate looks like a nice way to handle JDBC access without the need to write all that tedious connection code and exception handling stuff. However, unless I go to great effort I'd probably end up with SQL hard coded in my Java classes and I'd need to do all the resultset to object mapping by hand.

I discovered iBATIS recently almost by accident. iBATIS used to be a commercial product but has now been donated to the Apache Foundation. iBATIS is an O/RM-like approach. Clinton Begin, iBATIS creator, says that "iBATIS is not an O/RM. It does not bind classes to tables, nor does is it limited to OO languages and/or relational databases" and elsewhere iBATIS has been described as a convenience framework for JDBC. iBATIS does not offer some of the benefits that Hibernate does (database independence etc) but on the plus side it is very simple to use and even more so if you choose to use Spring's SqlMapClientTemplate.

I came across iBATIS as it was one of the technologies included as an example Jetspeed2 Portlet. iBATIS distribute JPetstore as an example of using Struts, DAO layer and iBATIS together. The Jetspeed2 version of the application uses the Struts bridge to convert the application into a portlet. The idea behind iBATIS is that all your SQL is kept in an external XML SQLMapping file. iBATIS then maps the returned result into a domain object.

Spring includes support for iBATIS interaction. I spent a little time studying the iBATIS JPetstore example and a version of this which actually uses Spring is further explored in Bruce Tate and Justin Gehtland's book Better, Faster, Lighter Java (excerpts of which can be found on the OnJava web site [Demonstrating Spring's Finesse, Persistence in Spring]).

There is a Perl script which can be used to generate java-beans sources and sql-map config files generator. There is now also some iBATIS support inside Middlegen tool for the generation of iBATIS SQLMapping XML files and associated domain object POJOs. Looking at the DAO approach used in Better, Faster, Lighter Java and similarly using Spring's iBATIS support it seemed very possible to me that I could extend the existing iBATIS Middlegen Plugin so that it would generate the required DAO classes to implement the architecture shown in the diagram below.

The default iBATIS Middlegen plugin generates the CRUD actions needed for the SQL mapping and creates the definition of each domain object. It was relatively straight forward to modify these basic examples to create DAO interfaces, DAO implementation (using Spring SQLMapClientTemplates) and also a Façade interface / implementation.

To do this I had to learn a to use the Velocity Templating Language (VTL) to extend Middlegen code but since I have some shell scripting and XSL experience this is not that daunting a task.

Using the default Middlegen iBATIS plugin you can create an SQL Mapping file and domain object POJO class. For this example I have created a single Table called ITEM with one column containing an ITEM_ID. The generated iBATIS XML SQLMapping file is shown below. Notice how this contains the full range of CRUD operations.

<?xml version='1.0'?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
    "http://www.ibatis.com/dtd/sql-map-2.dtd">

<!-- WARNING: This is an autogenerated file -->

<sqlMap>        
        <typeAlias alias="Item" type="mypackage.domain.Item"/>
        <!--
    <cacheModel id="$table.destinationClassName-cache" type="MEMORY">
        <flushInterval hours="24"/>
        <flushOnExecute statement="insertItem"/>
        <flushOnExecute statement="updateItem"/>
        <flushOnExecute statement="deleteItem"/>
        <property name="reference-type" value="WEAK" />
    </cacheModel>
        -->
    <resultMap class="Item" id="Item-result" >
        <result
                property="itemId"
                javaType="java.lang.String"
                column="ITEM_ID"
        />
    </resultMap>

    <select id="getItem"
        resultClass="Item"
        parameterClass="Item"
        resultMap="Item-result" >
        <![CDATA[
            select
                ITEM_ID
            from
                ITEM
            where
                ITEM_ID = #itemId#

        ]]>
    </select>

    <update id="updateItem"
        parameterClass="Item" >
        <![CDATA[
            update
                        ITEM
            set

            where
                ITEM_ID = #itemId#
        ]]>
    </update>

    <insert id="insertItem"
        parameterClass="Item" >
        <![CDATA[
            insert into ITEM
              (ITEM_ID )
            values
              (#itemId# )
        ]]>
    </insert>

    <delete id="deleteItem" parameterClass="Item"  >
        <![CDATA[
            delete from ITEM where ITEM_ID = #itemId#
        ]]>
    </delete>

</sqlMap>

The default Middlegen iBATIS plugin will generate corresponding transparent domain object class (business objects), one per table. The domain should capture the relationships between the various system entities much as an Entity Relationship Diagram does and this is why we can generate this from the database directly. The generated classes are a "bare" platform into which you should expect to add more sophisticated behaviours. These really should contain behaviour as you'll probably recall from object oriented programming first principles a class should contain data and methods. Obviously the precise behaviour cannot be generically generated as it is likely to be domain object specific. If you do not add additional behaviour at this point you may be guilty of using an Anemic Domain Model.

package mypackage.domain;

import java.io.Serializable;
import java.sql.Timestamp;
import java.math.BigDecimal;
import org.apache.commons.lang.builder.HashCodeBuilder;

/**
 * @author <a href="http://boss.bekk.no/boss/middlegen/">Middlegen</a>
 *
 */
public class Item implements Serializable 
{
    // fields
    /**
     * The itemId field
     */
    private java.lang.String itemId;

    // getters/setters
    /**
     * Returns the itemId
     *
     * @return the itemId
     */
    public java.lang.String getItemId() 
    {
        return itemId;
    }

    /**
     * Sets the itemId
     *
     * @param newItemId the new itemId
     */
    public void setItemId(java.lang.String newItemId) {
        this.itemId = newItemId;
    }


    /**
     *  Implementation of equals method.
     */
    public boolean equals(Object object) 
    {
        if (this == object)
        {
            return true;
        }
        if (!(object instanceof Item))
        {
            return false;
        }
        Item other = (Item)object;
        return
                  this.itemId.equals(other.itemId);      }

     /**
      * Implementation of hashCode method that supports the
      * equals-hashCode contract.
      */
/*
    public int hashCode()
    {
        return
             hashCode(this.itemId);     }
*/
     /**
      * Implementation of hashCode method that supports the
      * equals-hashCode contract.
      */
    public int hashCode() 
    {
        // TODO generate random number following the contract
        HashCodeBuilder builder = new HashCodeBuilder(17,37);
        return builder
            .append(itemId)
            .toHashCode();
    }

    /**
     *  Implementation of toString that outputs this object id's
     *  primary key values.
     */
    public String toString() 
    {
        StringBuffer buffer = new StringBuffer();
        buffer.append("itemId=");
        buffer.append(this.itemId);
            return buffer.toString();
        /*
        return
             this.itemId;           */
    }
}

I created Middlegen iBATIS Plugin extensions to generate the next few classes. This is an example of a generated DAO interface class. There will be one DAO interface class per domain object (i.e. one per table).

package mypackage.iface;

import  mypackage.domain.Item;

public interface ItemDao
{
    public Item getItem( java.lang.String itemId);
    public void insertItem(Item item);
    public void updateItem(Item item);
    public void deleteItem(Item item);

}

This is DAO implementation of the above interface using Spring's SqlMappingClientTemplate, again there will be one of these per domain object (i.e. one per table):

package mypackage.sqlmapdao;

import mypackage.domain.Item;
import mypackage.iface.ItemDao;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

public class SqlMapItemDao extends SqlMapClientDaoSupport implements ItemDao
{
    public Item getItem(java.lang.String itemId){
        Item item = new Item();
        item.setItemId(itemId);
    return (Item) getSqlMapClientTemplate().queryForObject("getItem",item);
    }

    public void insertItem(Item item) {
        getSqlMapClientTemplate().insert("insertItem",item);
    }

    public void updateItem(Item item){
        getSqlMapClientTemplate().update("updateItem",item);
    }

    public void deleteItem(Item item){
        getSqlMapClientTemplate().delete("deleteItem",item);
    }

}

In this most simple example the usage of a façade seems fairly pointless. The idea comes into it's own when you start to have more than one table of data represented in your domain. A façade collects all the publicly accessible DAO methods into a single interface. It also serves as an attachment point for other services, such as transaction support. In writing a Struts Action you would query against the façade rather than trying to obtain a DAO method directly. There will be only one instance of the façade layer interface and implementation it will likely contain references to all the DAO interfaces for every publicly accessible domain object.

See Persistence in Spring for more details about why we might want to generate a façade interface and implementation.

Façade interface:

package mypackage.domain.logic;

import mypackage.domain.Item;

public interface Façade
{

    public Item getItem( java.lang.String itemId);
    public void insertItem(Item item);
    public void updateItem(Item item);
    public void deleteItem(Item item);

}

Façade implementation:

package mypackage.domain.logic;

import mypackage.iface.ItemDao;
import mypackage.domain.Item;

public class FaçadeImpl implements Façade
{

    private ItemDao itemDao;

//-------------------------------------------------------------------------
// Setter methods for dependency injection
//-------------------------------------------------------------------------


    public void setItemDao(ItemDao itemDao) {
        this.itemDao = itemDao;
    }

//-------------------------------------------------------------------------
// Operation methods, implementing the Façade interface
//-------------------------------------------------------------------------



    public Item getItem( java.lang.String itemId){
    	return this.itemDao.getItem(itemId);
    }

    public void insertItem(Item item){
        this.itemDao.insertItem(item);
    }

    public void updateItem(Item item){
        this.itemDao.updateItem(item);
    }

    public void deleteItem(Item item){
        this.itemDao.deleteItem(item);
    }

}

As you can see from the above examples, I have now extended the Middlegen iBATIS Plugin to create a simple version of the entire Spring based DAO layer code. I'm currently looking into generating more complex domain relationship behaviour but this has so far only been slightly hampered by my limited VTL scripting skills but it is certainly possible to do this with Middlegen as the Hibernate and EJB plugins produce something similar. I am hoping to better capture one-to-many relationships in the domain model so that I can detect these and generate appropriate SQLMapping and Java code. For example if we added a new domain object called CATEGORY it might contain many ITEMS and could therefore our Category domain object might contain:

private List items;

public List getItems()
{
    return items;
}

public void setItems(List items)
{
    this.items = items;
}

The following could be generated inside an appropriate XML SQL Mapping file:

<select
    id="getItemsByCategoryCode"
    parameterClass="java.lang.String"
    resultMap="itemMap">        
    select
        item_id,
        item_name,
        category_code
    from
        items
    where
        category_code = #value#;
</select>

* where itemMap is already defined someplace.

The Spring DAO implementation of this could then look something like:

public List findItems(Category category){
    getSqlMapClientTemplate().queryForList("getItemsByCategoryCode",category);
}

public void createCategoryWithItems(Category category){
    getSqlMapClientTemplate().execute(new SqlMapClientCallback() {
         public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
                 executor.startBatch();
        for (Iterator it=category.getItems().iterator(); it.hasNext(); ) {
                Item item = (Item) it.next();
                executor.insert("insertItem", item);
            }
                 executor.executeBatch();
                 return null;
         }
 });
}

Nothing that I have generated so far is especially complicated but it is still nice to be able to generate basic business objects and a working DAO layer without much effort. I'd be happy to share the Velocity templates that I used to create these classes.

Subliminally I have been drawn towards looking at Spring. The attraction has reached critical mass and I have finally succumbed. It is not surprising that I should want to look at Spring as I have been constantly drip fed snippets about how magical Spring is in the many disparate Java related articles that I have been browsing through over the last few months.

I've heard much hype about Spring and was hoping to find a breathtaking and spectacular innovation, I didn't find exactly what I expected. Some of the stuff I found looked to be very useful, other bits simply left me bewildered.

Spring at its essence consists of two core parts, BeanFactory and Aspect Oriented Programming (AOP). From what I can tell the most widely used part is the BeanFactory. The only AOP examples I've seen seem to concentrate on how logging could be transparently integrated into Spring applications, I'm certain this is selling AOP short but jumping to Aspect oriented programming is not a paradigm shift I am comfortable about making at the moment.

There is something of a paradigm shift required to understand the principles behind the BeanFactory. Almost every Spring tutorial I have read will start with attempting to explain Inversion of Control (IoC) (aka "The Hollywood Principle" aka "don't call us, we call you" aka "Dependency Injection" [coined by Martin Fowler]). I tend to find that this has the immediate effect of sending me running for the hills but take heart as I have found that I have so far managed to successfully use Spring without actually understanding this particular concept fully. I suppose I am saying don't let the "IoC" explanations prevent you from using Spring!

There is a rumour going about that Spring frees you from writing web specific code, there looks to be some truth to this argument but I have certainly seen plenty of familiar and reassuring web specific stuff inside Spring.

It seems to me that Spring is more of a toolbox rather than a framework. I don't want to get into a semantic argument about what a framework is or isn't but to my mind Spring seems to be less about providing structure and more about providing tools. Spring interfaces well to existing technologies with which you may already be very familiar for example: caching (EHCache), scheduling (Quartz), MVC (Struts, JSF) and O/RM (Hibernate, iBATIS, Toplink). As you might expect from a general toolbox that deals with Beans there are also many other generically useful features that in places bare more than a passing resemblance to Bean and web related offerings from Jakarta Commons and elsewhere.

Spring and Struts

An "optional" component of Spring is its very own web based MVC architecture framework. Instead of writing Controllers, Struts Actions and ActionForms in the Spring MVC architecture everything is a bean. I'm not a MVC purist and I'm sure that there is theoretical merit in this, it is probably closer to true MVC etc.etc. I don't feel comfortable about moving to using Spring MVC as yet although this may change as I learn more about it and see more examples. The thing I like about Struts (and I expect JSF is similar) is the rigid structure it brings to a web applications. Since Spring removes some of these rules I would worry that you could lose some of the beneficial structure. I like the fact that I can hand my Struts application to a colleague with some Struts experience and they pretty much know what to expect without needing to reverse engineer anything or make a careful study of any of my configuration files.

It is also stated that Spring is not prescriptive about what technologies you should use. The Spring community are happy to talk to you even if you are sticking with Struts or JSF or whatever for your MVC implementation. Now you might see what I mean about Spring being more like a toolbox than a framework? There is inherent freedom of choice when using Spring, it provides some very useful tools, used with care it can create fantasically elegant solutions but it does nothing to prevent you from creating bad solutions.

Spring MVC has no apparent Dynabean support, granted real concrete beans aren't difficult to generate if you can find the right options in your IDE. Netbeans carefully hides it getter/setter generation behind a right click on the variable you'd like getter/setters for, click on "Refactor" and then choose to "Encapsulate Fields", obvious really!!!

Spring has a SpringBindingActionForm that looks like it could be used in a DynaActionForm like way but I could find no example documentation beyond the API itself about this class.

What I want to use Spring for

Spring contains some cool looking features but it seems that in several places you are hard pressed to find any example code or tutorials about them. I thought it might be safer to stick with the well documented and hopefully well worn and tested parts of Spring. After having briefly looked at Spring's JDBCTemplate and the other Spring O/RM interfaces to Hibernate, iBATIS, Toplink etc I decided that I wanted to use Spring in my Data Access Object (DAO) layer. I am currently more interested in getting the DAO architecture right (for once) rather than the actual technologies involved. At first glance it seemed to me that Spring would be a very useful and simple DAO implementation technology. I have also seen that Spring contains support for Oracle's perculiar BLOBs and CLOBs implementation which could be very useful for one of my other projects.

Integrating Struts and Spring

Having seen that is quite acceptable to use Struts with Spring I started investigating the various approaches of integrating the two. The first article I read about integrating Struts and Spring, Get a better handle on Struts actions, with Spring, sent me off in what I now consider to be completely the wrong direction.

This article talks about three approaches to incorporating access to Spring beans into Struts Actions. All very impressive but something doesn't feel right to me. I have decided to use Spring in the DAO layer and I feel that unless I start using Spring in some other way it should be confined to the DAO layer therefore I don't need a Spring bean aware Struts Action. After some research I had decided my Struts Action should communicate with my DAO layer via a façade. The DAO implementation may well be using Spring but my Struts Action does not need to know that.

Tags :

Over the last couple of weeks I have been writing a multi-page wizard application with a database backend. This has been a learning opportunity for me to look into technologies like Spring and iBATIS to see what they could offer me in this and future endeavours. The next few blog entries will discuss what I have learned so far about Wizards, Spring and finally iBATIS. Firstly a very quick look at the Wizard solutions I found and eventually discarded.

I wanted to write a simple multi-page wizard and decided to see what was available to make my life easier. There is a subtle difference between a web wizard and full workflow. I found that solutions that were designed for proper workflow that include support for state, events, versioning and resource management were too heavyweight for a simple web wizard application.

Struts Flow

Struts flow uses JSON to define the flow between web pages. On this occasion I didn't like the idea of having to define functionality in server side JavaScript. I decided against this approach because I want a simple solution and I want my colleagues to understand it. My colleagues are happy enough for me to wax lyrical about the pleasures of AJAX, BSF, Rhino, E4X etc. as long as they don't have to use it.

EasyWizard

I then looked at using EasyWizard (See also these articles [1], [2]). I liked the basic approach. I saw merit in the fact you can test the state transition in isolation. However, I didn't like the idea of hard coding the flow into Java classes something about this just felt wrong.

Spring Web Flow

I looked at Spring Web Flow, I liked the idea of being able to define the flow in a separate XML file. Although it seemed you couldn't easily get the same flexibility into the flows as you could with EasyWizard. It was promising but still not the simple solution I was hoping to find.

Spring's AbstractWizardFormController

Spring has a built in mechanism called AbstractWizardFormController. I found one very simple example of its usage, I couldn't find any further examples or documentation so I abandoned using it.

Decision

My final decision was not to use any special wizard framework. I wanted to keep it simple and none of the above solutions were that simple or for my needs justified the extra effort to seem worthwhile. It seemed simpler to me to implement my wizard in Struts.