Tuesday, January 20, 2009

Using Java enums with Ibatis framework

I've been working on quite a few projects lately that used Spring framework with Ibatis in persistence layer. I kinda like it, because it does not try to do more for you than you expect it to do (evil grin at Hibernate...). It's reasonably simple and easy to use, and beats using plain JDBC by a large margin.

One thing I was missing (and documentation was vague in this regard), was mapping Java enums to database columns. I solved the few cases where I encountered this by changing it to a simple String<>varchar mapping. Apart from being a bit inconvenient (string comparisons in java code, unable to use switch statements, etc), it's fine. But it turns out, Ibatis solves this quite nicely with it's own com.ibatis.sqlmap.engine.type.EnumTypeHandler. To use it, you have to define the javaType attribute in the resultMap for the enum property:


<sqlmap namespace="Account">

<!-- Result maps describe the mapping between the columns returned
from a query, and the class properties. A result map isn't
necessary if the columns (or aliases) match to the properties
exactly. -->
<resultmap id="AccountResult" class="com.mydomain.domain.Account">
<result property="id" column="ACC_ID">
<result property="firstName" column="ACC_FIRST_NAME">
<result property="lastName" column="ACC_LAST_NAME">
<result property="emailAddress" column="ACC_EMAIL">
<result property="myEnum" column="ACC_ENUM" javaType="com.mydomain.domain.Account$MyEnum">
</resultmap>

<!-- Select with no parameters using the result map for Account class. -->
<select id="selectAllAccounts" resultmap="AccountResult">
select * from ACCOUNT
</select>

<!-- Insert example, using the Account parameter class -->
<insert id="insertAccount" parameterclass="com.mydomain.domain.Account">
insert into ACCOUNT
values (
#id#, #firstName#, #lastName#, #emailAddress#, #myEnum#
)
</insert>
... skipped the rest of the methods
</sqlmap>




This enum is declared inside of the Account class, hence the $ in the class name above.


public class Account {

private int id;
private String firstName;
private String lastName;
private String emailAddress;

public enum MyEnum {
FIRST, SECOND
}
private MyEnum myEnum;
public MyEnum getMyEnum() {
return myEnum;
}
public void setMyEnum(MyEnum myEnum) {
this.myEnum = myEnum;
}

public int getId() {
return id;
}
... other getters and setters
}


That's all there is to it, no custom type handlers to write!