Custom Type Handlers in iBatis

Custom Type Handlers in iBatis

There are times when you need to convert the data being returned in your sql query to match the data type of your variable.

An example of this is converting from a sql date to a Calendar object for use with beans generated from an xsd.

The iBatis framework allows for the creation of custom type handlers for this very purpose.

In order to achieve this, we extend TypeHandlerCallback and pay particular attention to the implementation of the  following method

[java]public Object getResult(ResultGetter getter) throws SQLException {} [/java]

In the code snippet below, we use the ResultGetter to return the sql date which we then set on the Calendar object.

public class DateTypeHandler implements TypeHandlerCallback {

public Object getResult(ResultGetter getter) throws SQLException {
try {
Calendar c = Calendar.getInstance();
return c;
} catch (Exception e) {
throw new SQLException();

//more code   

Pretty easy hey?

All we need to do now is tell iBatis to use our custom handler. This is done by adding the following into our SqlMapConfig.xml file


This simple mapping tells iBatis to use our newly created class when dealing with the associated java type.

Your result property in the resultMap must be mapped correctly in order for this to work.

<result property="dateOfBirth" column="dateOfBirth"
javaType="java.util.Calendar" jdbcType="DATE" />

And there you have it. Custom type handlers made easy!

Leave a Reply

Your email address will not be published. Required fields are marked *