【问题标题】:How do I get a Map<String, Integer> from MyBatis? Cause: java.sql.SQLException: Invalid value for getInt() - 'NONE'如何从 MyBatis 获取 Map<String, Integer>?原因:java.sql.SQLException:getInt() 的值无效 - 'NONE'
【发布时间】:2018-12-07 19:22:38
【问题描述】:

我尝试关注Return HashMap in mybatis and use it as ModelAttribute in spring MVC(选项1)和Mybatis ResultMap is HashMap<String,Object>。我有

@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);

返回错误

尝试从结果集中获取列“键”时出错。原因:java.sql.SQLException:getInt() 的值无效 - 'NONE' ; SQL []; getInt() 的值无效 - 'NONE';嵌套异常是 java.sql.SQLException: Invalid value for getInt() - 'NONE'

查询在 MySQL 中运行良好并返回

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

好像没有使用@MapKey注解。


我试过了

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

但它给了

嵌套异常是 org.apache.ibatis.executor.ExecutorException: No constructor found in java.util.AbstractMap$SimpleEntry matching [java.lang.String, java.lang.Long]

也尝试过同样的错误。

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

【问题讨论】:

    标签: mybatis spring-mybatis


    【解决方案1】:

    我必须建立自己的课程,但我不喜欢它。我必须添加这么多代码才能从数据库中获取一个简单的键/值对,这太愚蠢了。

    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>
    

    【讨论】:

      【解决方案2】:

      你应该写以下,

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

      这是 option-1 的方式。

      【讨论】:

      • 那是地图的地图。为什么会有用?您将如何指定 2 个键?只有 2 个值,但这需要 3 个。大概您会为外部 Map 使用与内部 Map 相同的键,但那有什么意义呢?还不如在那时使用地图列表。
      • @Chloe 这是选项1的工作方式,对于外部映射的键“NONE”,内部映射是“key”->“NONE”,“total”-> 33。您可以转换Map&lt;String, Integer&gt; anotherMap = map.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, it -&gt; (int)it.getValue().get("total")));> 映射到 Map
      猜你喜欢
      • 1970-01-01
      • 2013-12-01
      • 1970-01-01
      • 2020-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多