Navigation: Home Java Tutorials Custom Type Handlers in iBatis
Custom Type Handlers in iBatis
Java - Tutorials
Thursday, 11 November 2010 12:05

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

 public Object getResult(ResultGetter getter) throws SQLException {} 

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();
 c.setTime(getter.getDate());
 return c;
 } catch (Exception e) {
 e.printStackTrace();
 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

<typeHandler
 javaType="java.util.Calendar"
 callback="za.co.reegz.tutorials.ibatis.DateTypeHandler"/>

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!

 

Twitter Feed

reegz786
Java developer with delusions of Flex.. Living the developers dream
reegz786
reegz786: Just got asked if I've ever heard about the Balanced Scorecard. @CubicThoughts

12 hour(s) ago from Twitter for Android

reegz786
reegz786: #Ubuntu now on #android #linux #ftw http://t.co/LEsOc6v9

12 hour(s) ago from Twitter for Android

reegz786
reegz786: Never do business with friends.

2 day(s) ago from Twitter for Android



powered by TweetXT!