Hibernate =未找到列

时间:2010-08-18 13:42:44

标签: java hibernate orm native-sql

我通过hibernate在java中运行聚合函数,由于某种原因它给了我这个错误:

INFO Binary:182 - could not read column value from result set: l_date; Column 'l_date' not found. 

当我运行MySQL查询时,列名是l_date和logins,我无法弄清楚为什么它没有找到它。

我在MySQL中测试过该查询并验证它确实有效。我的功能如下所示。

public List<Logins> getUserLoginsByMonth() {
     Session session = getSessionFactory().openSession();
     ArrayList<Logins> loginList = null; 

     try {
          String SQL_QUERY = "SELECT l_date as l_month, SUM(logins) as logins FROM (SELECT DATE_FORMAT(login_time, '%M') as l_date, COUNT(DISTINCT users) as logins FROM user_logins WHERE login_time > DATE_SUB(NOW(), INTERVAL 1 YEAR) GROUP BY DATE(login_time)) AS Z GROUP BY(l_month)";

          Query query = session.createSQLQuery(SQL_QUERY);
          List results = query.list();
          for(ListIterator iter = results.listIterator(); iter.hasNext() ) {
                Objects[] row = (Object[])iter.next();
                System.out.println((Date)row[0}]);
                System.out.println((BigInteger)row[1]);
          }

     }
     catch(HibernateException e) {
         throw new PersistenceDaoException(e);
     }
     finally {
         session.close();
     }            
}

1 个答案:

答案 0 :(得分:5)

您需要将别名添加为:

query.addScalar("l_month");
query.addScalar("logins");

然后调用query.list();

应该可以正常工作。 addScalar是SqlQuery的一部分。