简体   繁体   中英

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?

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.

I had the same issue, I ended up writing a custom setter on my POJO to convert the string value.

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

  public static MyEnum fromValue(String v){
     .... find the enum based on value 
  }
}

public class POJO {
   private   MyEnum myEnum;
   public void setMyEnum(String strV){
        myEnum=MyEnum.fromValue(strV)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM