MyBatis TypeHandler phantom errors

I’ve found another annoyance with MyBatis (there are many so be on the lookout for a long blog post that covers everything). This one has to do with how MyBatis handles missing TypeHandlers and required a bit of time stepping through their code.

If you have an object that contains a field whose type is not registered with the TypeHandler registry, MyBatis does not always produce a nice exception for you. Instead, it sometimes decides to return null instead of creating your object.

Here is an example:

 // The domain object
 public class MyDateTimeHolder {
   public DateTime someJodaDateTime;
 }

I’m using Joda’s DateTime object here. If you don’t register this with MyBatis, it can cause this code to fail:

MyDateTimeHolder holder = holderMapper.retrieve();
// holder is null here!!!

The fix is to register the TypeHandler like this:

TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, ds);
Configuration configuration = new Configuration(environment);
configuration.getTypeHandlerRegistry().register(DateTime.class, DateTimeTypeHandler.class);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s