Tag Archives: java

Annotation Mapping for Ordered Lists in Hibernate

Here’s another problem that has a simple solution that took me longer than I expected to find.

I am using Hibernate 3.2.5 as my ORM. In one case, I want to map a child collection of items as an ordered List, taking advantage of the database to do my ordering.

I’m using Annotations intead of the hbm.xml format for my mappings in this project. Whenever possible, I’m using javax.persistence mappings in preference too Hibernate’s annoations.

Referring to Java Persistence with Hibernate, the mapping looks quite complicated, using Hibernate’s annotations. With some experimentation, I found a simple solution, using just the javax.persistence mappings. For simplicity, I’ll show the example annotating the Item / Bid class idea we’re used to from the Hibernate Caveat Emptor example.

package com.stevideter.domain;
 
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
 
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
 
import org.apache.commons.collections.CollectionUtils;
 
@Entity
@Table(name = "ITEM")
public class Item implements Serializable {
 
  private static final long serialVersionUID = -7990110946186412551L;
  private Integer id;
  private List bids = new ArrayList();
 
  @Id
  public Integer getId() {
    return id;
  }
 
  public void setId(Integer id) {
    this.id = id;
  }
 
  @OneToMany(mappedBy="item",cascade=CascadeType.ALL)
  @OrderBy("userId,date,amount")
  public List getBids() {
    return bids;
  }
 
  private void setBids(List bids) {
    this.bids = bids;
  }
 
  public void addBid(Bid bid) {
    if (CollectionUtils.isEmpty(bids)) { bids = new ArrayList();}
    bids.add(bid);
    bid.setItem(this);
  }
 
  public void removeBid(Bid bid) {
    if (CollectionUtils.isNotEmpty(bids)) {
      bids.remove(bid);
    }
  }
 
}

And for reference, here’s the mapping in the Bid with the Item as a parent:

package com.stevideter.domain;
 
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
 
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
 
@Entity
@Table(name = "BID")
public class Bid implements Serializable {
 
  private static final long serialVersionUID = 8165733510722884274L;
  private Integer id;
  private Item item;
  private Date date;
  private BigDecimal amount;
  private Integer userId;
 
  @Id
  public Integer getId() {
    return id;
  }
 
  public void setId(Integer id) {
    this.id = id;
  }
 
  @ManyToOne( targetEntity = com.stevideter.domain.Item.class )
  @JoinColumn(name = "itemid", nullable = false)
  public Item getItem() {
    return item;
  }
 
  public void setItem(Item item) {
    this.item = item;
  }
 
  public Date getDate() {
    return date;
  }
 
  public void setDate(Date date) {
    this.date = date;
  }
 
  public BigDecimal getAmount() {
    return amount;
  }
 
  public void setAmount(BigDecimal amount) {
    this.amount = amount;
  }
 
  public Integer getUserId() {
    return userId;
  }
 
  public void setUserId(Integer userId) {
    this.userId = userId;
  }
 
}

With this mapping, the bids collection is managed by the Item, so saving the Item automatically saves the bid collection.

This example does follow the JPA standard of configuration by exception, so column names, etc., that are not explicitly called out follow the default standards.

What has been your trickiest Hibernate or javax.persistence mapping problem? How did you solve it?


Edited to make mapping on Bids properly bidirectional.

Finding selected checkbox items in a JSF dataTable

This is one of those problems that I couldn’t find a complete example for when I needed it, so hopefully this will save somebody else the extra time it took me to piece it together.

We frequently need to have data tables in our UI, and allow the user to select a subset of those items for action. In JavaServer Faces, this means having a DataTable, each row having its own checkbox. But when the action is triggered, how to we find which items the user has selected.

The first step is to add a boolean property to your objects that can represent the selection. If you have a lot objects in your domain that will need this property, you may want to consider adding this to an interface or parent bean, otherwise, you can add it directly to your domain object. As a caveat, I don’t like adding properties to my domain objects that are for UI use only, but in this case, I’m keeping this as simple as possible. Sometimes pragmatism wins.

package com.stevideter.domain;
 
public class SelectableItem {
 
  private Integer id;
  private String name;
  private boolean selected;
 
  public Integer getId() {
    return id;
  }
 
  public void setId(Integer id) {
    this.id = id;
  }
 
  public String getName() {
    return name;
  }
 
  public void setName(String name) {
    this.name = name;
  }
 
  public boolean isSelected() {
    return selected;
  }
 
  public void setSelected(boolean selected) {
    this.selected = selected;
  }
}

In your view, you’ll use the dataTable to display the items, including the checkbox:

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
 
<f:view><html><body>
<h:form>
<h:dataTable id="itemsTable" 
    value="#{SelectionBean.selectedItems}" var="item"  >
 
<f:facet name="header">
  <h:outputText value="Items" />
</f:facet> 
<h:column>
  <f:facet name="header">
    <h:outputText value="Select" />
  </f:facet>
  <h:selectBooleanCheckbox value="#{item.selected}" />
</h:column>
<h:column>
  <f:facet name="header">
    <h:outputText value="name" />  
  </f:facet> 
    <h:outputText value="#{item.name}"></h:outputText>
</h:column>
</h:dataTable>
<h:commandButton title="selectItems" 
    value="Select Items"
    actionListener="#{SelectionBean.submitSelections}" />
</h:form>
</body></html></f:view>

Now when you click the command button to trigger the submitSelections event, the boolean values for selected items will be set, and you can iterate through your list to find the selected items and act on them as needed.

package com.stevideter.BackingBean;
 
import java.util.List;
 
import javax.faces.event.ActionEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
 
import com.stevideter.domain.SelectableItem;
import com.stevideter.manager.DomainManager;
 
public class SelectionBean {
 
  private DataModel selectableItems;
  private DomainManager manager;
 
  public void populateSelectableItems(ActionEvent event) {
    selectableItems = new ListDataModel();
    selectableItems.add(manager.getSelectableItems());
  }
 
  public void submitSelections(ActionEvent event) {
    List<SelectableItem> items = (List<SelectableItem>)selectableItems.getWrappedData();
    List<SelectableItem> selectedItems = new ArrayList<SelectableItem>();
    for (SelectableItem item : items) {
      if (item.isSelected()) {
        selectedItems.add(item);
      }
    }
    // do what you need to do with selected items
  }
 
  public DataModel getSelectableItems() {
    return selectableItems;
  }
 
  public void setSelectableItems(DataModel selectableItems) {
    this.selectableItems = selectableItems;
  }
}

As you can see, this is a very simple solution. Have you seen any other approaches that work?

How to configure a secure JMS connection using Spring

In a comment to my previous post about configuring JMS via Spring, Vikas Kadam asked about configuring a connection to a secure TIBCO EMS topic or queue. As fate would have it, the next issue I dealt with was adding this to my own application. What worked for me was using Spring’s UserCredentialsConnectionFactoryAdapter as my connection factory for my JmsTemplate. The final configuration looked like this:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
 
  <bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location"
      value="file:${catalina.home}/conf/jms.properties" />
  </bean>
 
  <bean id="messageSender"
    class="com.stevideter.spring.jms.MessageSender">
    <property name="jmsTemplate" ref="jmsTemplate" />
  </bean>
 
  <bean id="jmsTemplate"
    class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory"
      ref="userCredentialsConnectionFactory" />
    <property name="defaultDestinationName"
      value="${jms.defaultdestinationname}" />
    <property name="pubSubDomain" value="${jms.istopic}" />
  </bean>
 
  <bean id="userCredentialsConnectionFactory"
    class="org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter">
    <property name="targetConnectionFactory">
      <ref bean="topicConnectionFactory" />
    </property>
    <property name="username" value="${jms.username}" />
    <property name="password" value="${jms.password}" />
  </bean>
 
  <bean id="topicConnectionFactory"
    class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiTemplate" ref="jndiTemplate" />
    <property name="jndiName"
      value="${jms.connectionfactory}" />
  </bean>
 
  <bean id="jndiTemplate"
    class="org.springframework.jndi.JndiTemplate">
    <property name="environment">
      <props>
        <prop key="java.naming.factory.initial">
          com.tibco.tibjms.naming.TibjmsInitialContextFactory
        </prop>
        <prop key="java.naming.provider.url">
          ${jms.jndicontexturl}
        </prop>
      </props>
    </property>
  </bean>
</beans>

Simplifying Spring’s JMS configuration for JndiTemplate

I’ve spent several days, off and on, wrestling with a chicken-and-egg configuration issue.

I have an application that uses Spring 2.0 and is deployed to Tomcat 5.5. We make heavy use of Tomcat’s JNDI for configuring things like our database connections.

We’re adding JMS functionality to our application; at this point, we merely need to send events to an existing Tibco EMS 4.4 Topic.

Following the various online tutorials, I was able to use Spring to make my JMS code very lightweight. I was pretty happy with things overall, until I encountered the final problem of setting up the configuration.

The Tibco EMS Server provides its own JNDI services, which I need to connect to the correct topic connection factory. I can use Spring’s JndiTemplate to configure this additional JNDI connection, but I kept hitting one problem. In every environment I’m going to deploy to, the value for java.naming.provider.url will be different. Because JndiTemplate is using

for setting the environment, I can’t use a separate JNDI lookup to populate that value out of Tomcat’s JNDI.

I needed to abstract this value out of my war file, into a configuration file that can stay on each server, so I don’t have to change it every time. This is an application that gets deployed fresh each new revision, and the client wasn’t going to be happy to have to extract the war file and then edit a config file, when that’s never been needed in the past. In addition, each server we’re deploying to already has a JNDI configuration for the Tibco EMS server. But, no matter how I tried, I could not find a way to configure the Tomcat JNDI to let me access those values from the Spring configuration file within the application.

The solution I found that finally worked was to use a PropertyPlaceholderConfigurer that pointed to a file in the tomcat conf directory. The final hurdle I had to jump was the correct configuration. If I used property=”location” value=”${catalina.home}/conf/jms.properties”, Spring would attempt to resolve the value from the servlet container by prepending a slash in front of the catalina.home directory. If I attempted to use a relative path, tomcat wouldn’t allow me open and read the file. I finally hit on prefixing the path with “file:” which was the magic to let Spring know I meant an absolute file path.

I am annoyed I have to add a configuration file, but at least it’s one more place where we can set the value and forget about it for future deployments.

In case anybody hits this combination of problems, here’s what finally worked:

<?xml version="1.0" encoding="UTF-8"?>
 
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
       http://www.springframework.org/schema/jee 
       http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
 
           <bean id="propertyConfigurer"
            class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations">
                <list>
                    <value>file:${catalina.home}/conf/jms.properties</value>
                    <value>/WEB-INF/jdbc.properties</value>
                </list>
            </property>
        </bean>
 
    <bean id="messageSender"  
             class="com.stevideter.spring.jms.MessageSender">
        <property name="jmsTemplate" ref="jmsTemplate" />
    </bean>
 
    <bean id="jmsTemplate" 
              class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="topicConnectionFactory" />
        <property name="defaultDestinationName">
            <jee:jndi-lookup jndi-name="java:comp/env/jms/eventdestname"/>
        </property>
        <property name="pubSubDomain" value="true" />
    </bean>
 
    <bean id="topicConnectionFactory" 
             class="org.springframework.jndi.JndiObjectFactoryBean">
       <property name="jndiTemplate" ref="jndiTemplate"/>
       <property name="jndiName" value="FTTopicConnectionFactory"/>
    </bean>
 
    <bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
           <property name="environment">
                  <props>
                         <prop key="java.naming.factory.initial">
                            com.tibco.tibjms.naming.TibjmsInitialContextFactory
                         </prop>
                         <prop key="java.naming.provider.url">
                            ${jms.jndicontexturl}
                         </prop>
                  </props>
           </property>
    </bean>
</beans>

Understanding the protected access modifier and inheritance in Java

The Java Tutorial gives the standard definition of the protected access modifier:

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

But what does this mean in practice? I see a lot of confusion that can be best cleared up by showing some code. Below are five classes. The first three are in one package, the second two in another:

package com.stevideter.java;
 
public class X {
    protected void doSomething() {
        System.out.println("did something");
    }
}
package com.stevideter.java;
 
public class Y extends X {
 
    protected void doSomethingElse() {
        // inherited from X
        super.doSomething();
        X x = new X();
        // visible b/c of same package
        x.doSomething();
    }
}
package com.stevideter.java;
 
public class AccessTest {
    public static void main(String[] args) {
        X x = new X();
        // visible - same package
        x.doSomething();
        Y y = new Y();
        // visible - inherited in same package
        y.doSomething();
    }
 
}
package com.stevideter.java.examples;
 
import com.stevideter.java.X;
import com.stevideter.java.Y;
 
class Z extends X {
    protected void myDoSomething() {
        // can call as part of implementation
        super.doSomething();
        X x = new X();
        x.doSomething(); // compile time error; declared in different package
    }
}
 
public class ExternalAccessTest {
 
    public static void main(String[] args) {
        X x = new X();
        x.doSomething(); // compile-time error, not visible
        Y y = new Y();
        y.doSomething(); // compile-time error, not visible
        Z z = new Z();
        z.doSomething(); // compile-time error, not visible
        z.myDoSomething();
    }
 
}

Here we see that while we operate in the same package, we can always access class X’s protected method doSomething(). Subclass Y can access it via inheritance, and AccessTest can see doSomething() for X, because it’s in the same package, and Y because Y inherited it from X and is in the same package.

In the second package, we see that access to X’s protected method is far more restricted. Subclass Z can use doSomething() as part of its own implementation. But it cannot access it via an instance of X.

ExternalAccessTest, on the other hand, simply cannot see doSomething(). This is true for X, because X and ExternalAccessTest are in different packages. But perhaps it’s surprising that it cannot see it in Z, which is in the same package as ExternalAccessTest. The reason is that although Z inherits doSomething from its parent class X, because doSomething() is in fact declared in a different package, that method is not visible in the new package.

It’s this final case that seems to cause the most confusion. Z does inherit the protected method doSomething(). But that inheritance is restricted by that protected access modifier. The inheritance doesn’t “override” the original declaration.

Why Are All My Collection Elements the Same as the Last One I Added?

I’ve seen several programmers struggle with a similar question. They create a collection of some sort, and add items to it in a loop. When they finish the loop and try to use the collection (or list, or array, or set, or map) it looks like every single object in the collection is the same one — the last one added to the array. Usually they’ve written code that looks something like this C# example:

using System;
using System.Collections.Generic;
 
namespace Stevideter.ArrayTest
{
    public class Program
    {
        static void Main(string[] args)
        {
 
            List<Person> people = new List<Person>();
            Person person = new Person();
            for (int i = 0; i < 3; i++)
            {
                person.Name = String.Format("Person {0}", i);
                person.Age = i * i;
                people.Add(person);
            }
 
            foreach (Person person1 in people)
            {
                Console.Out.WriteLine(person1);
            }
        }
    }
 
    class Person
    {
        private String name;
        public String Name
        {
            get { return name; }
            set { name = value; }
        }
 
        private int age;
        public int Age
        {
            get { return age; }
            set { age = value; }
        }
 
        public override string ToString()
        {
            return String.Format("{0} is {1}",name,age);
        }
    }
}

What happened? Why is the output:

Person 2 is 4
Person 2 is 4
Person 2 is 4

The answer is in the mystery that is parameter passing by value.

In both Java and C#, parameters are passed by value. But what this means for objects is not what you may intuitively expect. When you pass an object reference to a parameter, the value that is passed is, in fact, a copy of the reference, not a copy of the object that is referenced. Both the original reference and the value copy point to the same object. That is why you can update the members of an object in a method that you pass it to – you have a copy of the address where that object lives on the heap.

In the code above, only one Person is created. Each trip through the loop, the members of
person are updated. When people.Add(person) is called, the reference to the object created by new Person() is copied and added to the List people.

When you change the object’s values the next time through, every reference to that object sees the changes, because they all still point to the same instance on the heap. This is why at the end, every item in the array has the most recent updates. The code, as usual, is doing exactly what you told it to do.

Instead, you need to create a new object for each object you want in the array, and add that new reference to the array. This time, let’s see it in Java:

package com.stevideter.java;
 
import java.util.ArrayList;
import java.util.List;
 
public class ArrayTest {
 
    public static void main(String[] args) {
 
        List<Person> people = new ArrayList<Person>();
        for (int i = 0; i < 3; i++) {
            Person person = new Person();
            person.setName(String.format("Person %d", i));
            person.setAge(i*i);
            people.add(person);
        }
 
        for (Person person : people) {
            System.out.println(person.toString());
        }
    }
}
 
class Person {
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return String.format("%s is %d", name, age);
    }
}

This time we get the results we probably expected:

Person 0 is 0
Person 1 is 1
Person 2 is 4

At this point, you might be confused by the issue of scope, and feel you must declare and instantiate the object outside of the loop, afraid of losing the object when the loop ends.

What is actually lost when we leave the for loop is access to the reference person.
But the references to the heap location for the object created by each call to new Person() still exist. So the objects are still in the heap, and can still be used via the array/collection to which they were added.

I know I still get caught now and again by the implications of pass by value in Java and C#. When is the last time it surprised you?

Using parent bean definitions in Spring

This post on the JavaRanch Big Moose Saloon led me to fire up Eclipse and write some test code. The question is basically how can you use the ability to map a parent bean as part of a bean definition in Spring.

Let’s look at three classes and see how they can be mapped using Spring.

public abstract class SuperBean {
	private int id;
	private String name;
 
	public int getId() {
		return id;
	}
 
	public void setId(int id) {
		this.id = id;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
}
 
public class SubBean extends SuperBean {
 
	private String newProperty;
 
	public String getNewProperty() {
		return newProperty;
	}
 
	public void setNewProperty(String newProperty) {
		this.newProperty = newProperty;
	}
 
}
 
public class DifferentBean {
	private int id;
	private String name;
	private String myProperty;
 
	public int getId() {
		return id;
	}
 
	public void setId(int id) {
		this.id = id;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public String getMyProperty() {
		return myProperty;
	}
 
	public void setMyProperty(String myProperty) {
		this.myProperty = myProperty;
	}
 
}

now let’s map them in Spring:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
 
    <bean id="superBean" abstract="true"
        class="com.stevideter.spring.SuperBean">
        <property name="id" value="1" />
        <property name="name" value="superBean" />
    </bean>
 
    <bean id="subBean" class="com.stevideter.spring.SubBean"
        parent="superBean">
        <property name="id" value="2" />
        <property name="newProperty" value="subBean" />
    </bean>
 
    <bean id="differentBean" class="com.stevideter.spring.DifferentBean"
        parent="superBean">
        <property name="id" value="3" />
        <property name="myProperty" value="differentBean" />
    </bean>
</beans>

And now let’s write a simple app to show what happens with these mappings:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class TestClass {
 
    public static void main(String[] args) {
 
        ApplicationContext context = new ClassPathXmlApplicationContext(
                new String[] {"applicationContext.xml"});
 
        SubBean subBean = (SubBean)context.getBean("subBean");
        System.out.printf("ID: %d, Name: %s, Property: %s\n",
                                subBean.getId(), subBean.getName(), subBean.getNewProperty());
 
        DifferentBean differentBean = (DifferentBean)context.getBean("differentBean");
        System.out.printf("ID: %d, Name: %s, Property: %s\n",
                                differentBean.getId(), differentBean.getName(),
                                differentBean.getMyProperty());
    }
}

If we run this class, we get the following results:

ID: 2, Name: superBean, Property: subBean
ID: 3, Name: superBean, Property: differentBean

What we learn from this is that you can use the parent attribute to map to a parent bean definition that your bean class doesn’t inherit from. What’s necessary is that the classes are compatible, which means that the child class has all the properties that are defined in the parent class. In fact, the documentation notes you don’t have to declare a class on the parent definition at all.

I find it more useful to think of the parent definition as a template, to avoid the trap of thinking it is an object-oriented style of inheritance. Another way to think of it is as a parent interface for the child bean; you must implement these properties in order to use this definition.

JTOpen: Open source OS/400 and i5/OS drivers

My most recent project required me to use JDBC to connect to the database server on an OS/400 server. I had a heck of a time finding drivers, going around and around again on IBM’s site. The client probably had the drivers, but they were relying on us to tell them what went where and when.

All the documentation I could find seemed to say I needed IBM’s proprietary drivers, and a license key to boot. I found this a tad frustrating, to say the least.

Finally, a coworker’s google-fu broke the logjam as we discovered that there is, indeed, open source drivers for JDBC with the OS/400. The project is called JTOpen.

For the database connection string, the following format worked for us:

jdbc.url=jdbc:as400:DBNAME
jdbc.username=DBUSER
jdbc.password=DBPASSWORD

Processing Stored Procedure result sets in Spring

Recently, I was using Spring‘s JDBCTemplate for my Data Access Layer (DAL). I had a stored procedure that returned a result set, and had to spend quite a bit of search time finding an example of how to process it.

I managed to work it out using both the method of overriding Spring’s StoredProcedure and using the simple JDBCTemplate.query(sql, args, rowMapper). I found the latter to be simpler, since it doesn’t involve a inner class, etc., so here’s a complete example for anyone else who might need to try. Note the assumption that this is a Spring-managed application, so the dataSource is being injected.

This works as early as Spring 1.2.9 and Java 1.3.

package com.stevideter.business.dal.spring;
 
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
 
import javax.sql.DataSource;
 
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
 
import com.stevideter.business.Customer;
import com.stevideter.business.ApplicationException;
 
/**
 * CustomerSpringDao ...
 * @author stevi.deter@gmail.com
 * @version     %I%, %G%
 * @since       1.0
 **/
 
public class CustomerSpringDao {
 
    private JdbcTemplate jdbcTemplate;
 
    public Customer get(Long accountNumber) throws ApplicationException {
        if (accountNumber == null) {
            throw new IllegalArgumentException();
        }
        if (getJdbcTemplate() == null) {
            throw new ApplicationException(ApplicationException.NULL_DAO);
        }
        try {
            List customers = getJdbcTemplate().query(
                    "call PACKAGE.GET_CUSTOMER(?)",
                    new Object[] { accountNumber }, new CustomerMapper());
            if (CollectionUtils.isNotEmpty(customers)) {
                // return the first one
                return (Customer)customers.get(0);
            }
            return null;
        } catch (DataAccessException ex) {
            throw new ApplicationException(ApplicationException.DATA_ACCESS_ERROR);
        }
    }
 
    /**
    * CustomerMapper processes a ResultSet to populate a Customer object
    * @author stevi.deter@gmail.com
    * @version     %I%, %G%
    * @since       1.0
    *
     */
    protected static final class CustomerMapper implements RowMapper {
 
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            Customer customer = new Customer();
            customer.setAccountNumber(new Long(rs.getLong("ACCOUNTNUMBER")));
            customer.setLastName(StringUtils.trimToNull(rs.getString("LASTNAME")));
            customer.setFirstName(StringUtils.trimToNull(rs.getString("FIRSTNAME")));
            return customer;
        }
    }
    /**
     * Spring DI for the datasource. instantiates the JdbcTemplate
     * @param dataSource
     */
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }
    /**
     * @return the jdbcTemplate
     */
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }
}