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);