Search code examples
mybatisspring-mybatis

How do I get a Map<String, Integer> from MyBatis? Cause: java.sql.SQLException: Invalid value for getInt() - 'NONE'


I tried to follow Return HashMap in mybatis and use it as ModelAttribute in spring MVC (Option 1) and Mybatis ResultMap is HashMap<String,Object>. I have

@Select("select sources.host as 'key', count(*) total ... group by host")
@MapKey("key")
Map<String, Integer> getSourcesById(@Param("id")String id, @Param("hitDate")Date hitDate);

It returns an error

Error attempting to get column 'key' from result set. Cause: java.sql.SQLException: Invalid value for getInt() - 'NONE' ; SQL []; Invalid value for getInt() - 'NONE'; nested exception is java.sql.SQLException: Invalid value for getInt() - 'NONE'

The query works fine in MySQL and returns

| key         | total |
+-------------+-------+
| NONE        |    33 |
| twitter.com |     1 |

It's as if it is not using the @MapKey annotation.


I tried

List<AbstractMap.SimpleEntry<String, Integer>> getSourcesById(...)

But it gave

nested exception is org.apache.ibatis.executor.ExecutorException: No constructor found in java.util.AbstractMap$SimpleEntry matching [java.lang.String, java.lang.Long]

Also tried this with the same error.

List<AbstractMap.SimpleEntry<String, Long>> 

https://docs.oracle.com/javase/7/docs/api/java/util/AbstractMap.SimpleEntry.html#constructor_summary

MyBatis 3.4.6, MyBatis-Spring 1.3.2


Solution

  • I had to build my own class, but I don't like it. It's dumb that I have to add so much code for getting a simple key/value pair from the DB.

    Pair.java
    public class Pair<T1, T2> {
        public T1 key;
        public T2 value;
    
        public Pair(T1 k, T2 v) {
            key = k;
            value = v;
        }
        
        public Pair(String k, Long v) {
            key = (T1) k;
            value = (T2) v;
        }
    
        public T1 getKey() {
            return key;
        }
    
        public T2 getValue() {
            return value;
        }
    
    }
    
    Mapper.java
    List<Pair<String, Long>> getSourcesById(@Param("id")String id, @Param("hitDate")Date hitDate);
    
    Page.jsp
    <c:forEach items="${sources}" var="s">${s.value},</c:forEach>