Handling Enums
If you want to map an Enum
, you’ll need to use either EnumTypeHandler
or EnumOrdinalTypeHandler
.
For example, let’s say that we need to store the rounding mode that should be used with some number if it needs to be rounded. By default, MyBatis uses EnumTypeHandler
to convert the Enum
values to their names.
Note EnumTypeHandler
is special in the sense that unlike other handlers, it does not handle just one specific class, but any class that extends Enum
However, we may not want to store names. Our DBA may insist on an integer code instead. That’s just as easy: add EnumOrdinalTypeHandler
to the typeHandlers
in your config file, and now each RoundingMode
will be mapped to an integer using its ordinal value.
<!-- mybatis-config.xml -->
<typeHandlers>
<typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler"
javaType="java.math.RoundingMode"/>
</typeHandlers>
But what if you want to map the same Enum
to a string in one place and to integer in another?
The auto-mapper will automatically use EnumOrdinalTypeHandler
, so if we want to go back to using plain old ordinary EnumTypeHandler
, we have to tell it, by explicitly setting the type handler to use for those SQL statements.
(Mapper files aren’t covered until the next section, so if this is your first time reading through the documentation, you may want to skip this for now and come back to it later.)
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.apache.ibatis.submitted.rounding.Mapper">
<resultMap type="org.apache.ibatis.submitted.rounding.User" id="usermap">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="funkyNumber" property="funkyNumber"/>
<result column="roundingMode" property="roundingMode"/>
</resultMap>
<select id="getUser" resultMap="usermap">
select * from users
</select>
<insert id="insert">
insert into users (id, name, funkyNumber, roundingMode) values (
#{id}, #{name}, #{funkyNumber}, #{roundingMode}
)
</insert>
<resultMap type="org.apache.ibatis.submitted.rounding.User" id="usermap2">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="funkyNumber" property="funkyNumber"/>
<result column="roundingMode" property="roundingMode"
typeHandler="org.apache.ibatis.type.EnumTypeHandler"/>
</resultMap>
<select id="getUser2" resultMap="usermap2">
select * from users2
</select>
<insert id="insert2">
insert into users2 (id, name, funkyNumber, roundingMode) values (
#{id}, #{name}, #{funkyNumber}, #{roundingMode, typeHandler=org.apache.ibatis.type.EnumTypeHandler}
)
</insert>
</mapper>
Note that this forces us to use a resultMap
instead of a resultType
in our select statements.