Search code examples
javahibernateormnative-sql

Hibernate = Column not found


I am running an aggregate function in java through hibernate and for some reason it is giving me this error:

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

When I run the MySQL query the column names are l_date and logins and I can not figure out why it is not finding that.

I have tested the query in MySQL and verified that it does work. My function looks as follows.

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();
     }            
}

Solution

  • You need to add aliases as:

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

    and then call query.list();

    It should work fine. addScalar is part of SqlQuery.