Tuesday, March 20, 2012

Mapping enum java types as numbers by MyBatis

MyBatis provide EnumTypeHandler which allows to maps Java enumeration types to database as strings. String representation is good option, because values are directly readable from database, although there is one case when number representation is better. For example look at following enumeration:

Constant READ represent lowest possible access level. WRITE implicitly include READ access, and of course OWNER includes WRITE and READ accesses together. Now imagine SQL query which selects all documents where user specified by ID has access specified by accessLevel:

If access level is stored in database as string the query above isn't correct. But when we replace string representation by numbers, query works as expected.
READ1
WRITE2
OWNER3

How to alter standard behavior of MyBatis to map some java enumeration types as a string? Answer is: by implementing custom TypeHandler:

It would be nice if we can register the handler with specific java enumeration types like this:

But the configuration above is not valid yet! You have to implement your own EnumOrderTypeHandler and extend it for every java enumeration type:

and than register extended handler: