mybatis- 3.1.1. how to override the resultmap returned from mybatis

懵懂的女人 提交于 2019-11-29 08:52:23
quux00

I'm afraid the answer is that MyBatis doesn't provide any direct way to control the case of the keys in a result map. I asked this question recently on the MyBatis Google Group: https://groups.google.com/forum/?fromgroups#!topic/mybatis-user/tETs_JiugNE

The outcome is dependent on the behavior of the JBDC driver.

It also turns out that doing column aliasing as suggested by @jddsantaella doesn't work in all cases. I've tested MyBatis-3.1.1 with three databases in the past: MySQL, PostgreSQL and H2 and got different answers. With MySQL, the case of the column alias does dictate the case of the key in the hashmap. But with PostgreSQL it is always lowercase and with H2, it is always uppercase. I didn't test whether column aliases will work with Oracle, but by default it appears to return capital letters.

I see two options:

Option 1: Create some helper method that your code will always use to pull the data out of the returned map. For example:

private Object getFromMap(Map<String, Object> map, String key) {
  if (map.containsKey(key.toLowerCase())) {
    return map.get(key.toLowerCase());
  } else {
    return map.get(key.toUpperCase());
  }
}


Option 2: Write a LowerCaseMap class that extends from java.util.AbstractMap or java.util.HashMap and wrappers all calls to put, putAll and/or get to always be lower case. Then specify that MyBatis should use your specific LowerCaseMap rather than a standard HashMap, when populating the data from the query.

If you like this idea and want help on how to tell MyBatis how to use a different concrete collection class, see my answer to this StackOverflow question: https://stackoverflow.com/a/11596014/871012

What if you modify the query so you get the exactly column name you need? For example:

select my_column as MY_COLUMN from ...

The idea of a LowerCaseMap as the ResultType is sound, but you can probably avoid writing your own. In my case I'm using org.apache.commons.collections.map.CaseInsensitiveMap:

<select id="getTableValues" 
        resultType="org.apache.commons.collections.map.CaseInsensitiveMap">
      SELECT *
        FROM my_table
       WHERE seq_val=#{seq_val}
</select>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!