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.

  1. <!-- mybatis-config.xml -->
  2. <typeHandlers>
  3. <typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler"
  4. javaType="java.math.RoundingMode"/>
  5. </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.)

  1. <!DOCTYPE mapper
  2. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="org.apache.ibatis.submitted.rounding.Mapper">
  5. <resultMap type="org.apache.ibatis.submitted.rounding.User" id="usermap">
  6. <id column="id" property="id"/>
  7. <result column="name" property="name"/>
  8. <result column="funkyNumber" property="funkyNumber"/>
  9. <result column="roundingMode" property="roundingMode"/>
  10. </resultMap>
  11. <select id="getUser" resultMap="usermap">
  12. select * from users
  13. </select>
  14. <insert id="insert">
  15. insert into users (id, name, funkyNumber, roundingMode) values (
  16. #{id}, #{name}, #{funkyNumber}, #{roundingMode}
  17. )
  18. </insert>
  19. <resultMap type="org.apache.ibatis.submitted.rounding.User" id="usermap2">
  20. <id column="id" property="id"/>
  21. <result column="name" property="name"/>
  22. <result column="funkyNumber" property="funkyNumber"/>
  23. <result column="roundingMode" property="roundingMode"
  24. typeHandler="org.apache.ibatis.type.EnumTypeHandler"/>
  25. </resultMap>
  26. <select id="getUser2" resultMap="usermap2">
  27. select * from users2
  28. </select>
  29. <insert id="insert2">
  30. insert into users2 (id, name, funkyNumber, roundingMode) values (
  31. #{id}, #{name}, #{funkyNumber}, #{roundingMode, typeHandler=org.apache.ibatis.type.EnumTypeHandler}
  32. )
  33. </insert>
  34. </mapper>

Note that this forces us to use a resultMap instead of a resultType in our select statements.