Search code examples
javahibernatehql

Error while executing HQL with group by clause


I am using the following HQL query:

 List<Object> object = session.createQuery("select userId, count(*) from Tweet " +
                "group by userId", Object.class).getResultList();

It's causing the following error:

Caused by: org.hibernate.query.QueryTypeMismatchException: Query result-type error - multiple selections: use Tuple or array at org.hibernate.query.sqm.internal.QuerySqmImpl.checkQueryReturnType(QuerySqmImpl.java:367) at org.hibernate.query.sqm.internal.QuerySqmImpl.visitQueryReturnType(QuerySqmImpl.java:328) at org.hibernate.query.sqm.internal.QuerySqmImpl.(QuerySqmImpl.java:227) at org.hibernate.internal.AbstractShare


what could be the reason for this? Is it because I am selecting specific columns in it?


Solution

  • Your select clause is returning two things, therefore the type signature of the method should be List<Object[]>. Use this version:

    List<Object[]> object = session.createQuery("select userId, count(*) from Tweet " +
                "group by userId", Object[].class).getResultList();
    

    But note that you could also define an entity which matches the select clause. Then, you could avoid the cumbersome Object[] result set type.