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

前端 未结 3 1318
臣服心动
臣服心动 2020-12-18 16:13

we using mybatis 3.1.1.

we found for oracle the result map returned contains column name in Capital letters and in case of mySql the result map returned contains col

相关标签:
3条回答
  • 2020-12-18 16:31

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

    select my_column as MY_COLUMN from ...
    
    0 讨论(0)
  • 2020-12-18 16:47

    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.collections4.map.CaseInsensitiveMap:

    <select id="getTableValues" 
            resultType="org.apache.commons.collections.map.CaseInsensitiveMap">
          SELECT *
            FROM my_table
           WHERE seq_val=#{seq_val}
    </select>
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题