【问题标题】:Return Map from hibernate从休眠返回地图
【发布时间】:2016-06-29 12:55:12
【问题描述】:

我正在尝试从 HQL 创建一个 Map 对象

这是我的代码

我遇到了异常:

java.lang.ClassCastException: java.util.ArrayList 无法转换为 java.lang.Long

List<Map<Long, Long>> test = new ArrayList<Map<Long, Long>>();
try {
    String HQL_QUERY = "select new map(hp.col1, hp.col2) from HP hp where hp.col1 in (:id)";
    test = getSession().createQuery(HQL_QUERY).setParameter("id", id).list();
}catch(Exception e){

}

不知道我在哪里犯错

请帮忙

【问题讨论】:

    标签: java hibernate hql


    【解决方案1】:

    HQL 就是这样工作的:

    List<MyObject> test = new ArrayList<>();
    try {
        String HQL_QUERY = "select new map(hp.col1, hp.col2) from HP hp where hp.col1 in (:id)";
        test = getSession().createQuery(HQL_QUERY).setParameter("id", id).getResultlist();
    }
    

    所以你应该改变你的属性类型,然后你可以编写一些代码来将你的列表转换为地图

    【讨论】:

      【解决方案2】:

      hp.col1hp.col1 正在返回 java.util.ArrayList,它应该是 Long。在实体类中更改它的类型。

      更改测试类型: List&lt;Map&lt;List, Long&gt;&gt; test = new ArrayList&lt;Map&lt;List, Long&gt;&gt;();

      【讨论】:

      • 我试过这个 List> test = new ArrayList>(); ...它不工作
      【解决方案3】:

      我犯了一个错误

      我需要使用参数列表而不是参数。

      代码如下:

       List<Map<Long, Long>> test = new ArrayList<Map<Long, Long>>();
      try {
          String HQL_QUERY = "select new map(hp.col1, hp.col2) from HP hp where hp.col1 in (:id)";
          test = getSession().createQuery(HQL_QUERY).setParameter("id", id).list();
      }catch(Exception e){
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-06
        相关资源
        最近更新 更多