简体   繁体   中英

Is there a way to use the enum ordinal in a foreach in MyBatis

I'm trying to filter a select-query with mybatis dynamically in a foreach loop.

Here's an example from my xml mapper:

<if test="array!= null and array.length > 0">
   AND arrayValCol IN
      <foreach item="item" collection="array" separator="','" open="('" close="')">
         ${item}
      </foreach>
</if>

But the array contains enums as values and I'm couldn't find any solution in the mybatis documentation or with google.

Is there a way to solve this at all?

  • By default, MyBatis uses EnumTypeHandler which calls name() method when binding enum parameters. You need to tell MyBatis to use EnumOrdinalTypeHandler instead.
  • You should use #{} instead of ${} whenever possible. See the FAQ .
<if test="array!= null and array.length > 0">
  AND arrayValCol IN
  <foreach item="item" collection="array" separator="," open="(" close=")">
    #{item,typeHandler=org.apache.ibatis.type.EnumOrdinalTypeHandler}
  </foreach>
</if>

It is also possible to change the default enum type handler by specifyingdefaultEnumTypeHandler in configuration.

<settings>
  <setting name="defaultEnumTypeHandler"
    value="org.apache.ibatis.type.EnumOrdinalTypeHandler"/>
</settings>

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