Search code examples
javaenumsmappingibatis

mapping enum on ibatis


I have an enum something like this

public Enum MyEnum { 
  NEW("NEW"),
  OLD("OLD"),
  IN_PROCESS("IN PROCESS");
}

The mapping on ibatis works fine for the NEW and OLD, but encounters an error when the IN_PROCESS is encountered since the value of my IN_PROCESS in the DB is IN PROCESS, and the error indicates that ibatis tries to find an enum with that value, can someone suggest a solution?


Solution

  • MyBatis use an EnumTypeHandler to do mappings with enums. In this Enum type handler it uses the name() method of the Enums which returns the string value of the variable name. For example NEW -> "NEW" and IN_PROCESS -> "IN_PROCESS".

    Otherwise, to get the value it uses Enum.valueOf(type, s); which gets the value of the Enum through the String value which corresponds with the variable name ("NEW" -> MyEnum.NEW, "IN_PROCESS" -> MyEnum.IN_PROCESS) and internally is used the method name().

    You cannot overwrite name() because is marked as final so you options are:

    1. The easy way is to use IN_PROCESS instead of IN PROCESS. I prefer this, is easier and fast.

    2. The second option is create your TypeHanlder for this enum and check if the parameter is IN PROCESS and search with IN_PROCESS.