Search code examples
javahibernatehql

Not able to fetch resultset in Hibernate using HQL


I'm triggering a query using HQL, normally it should return empty resultset as it doesn't have any records w.r.t it. But, it throws

org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)

My code is

String hql = "FROM com.pck.Person where userId = " + userId;
Query query = session.createQuery(hql);         
@SuppressWarnings("unchecked")
List<Dashboard> listUserDetails = query.list(); <-- Problem here.

I'm expecting list size is 0 because there are no records w.r.t userId passed.

What changes do I need to do?


Solution

  • Lets say the value of userId was "abc12"

    Given your code, the value of the string called hql would become: "FROM com.pck.Person where userId = abc12"

    If you took the value of that string and tried to run it as a query on any database, most of them would fail to understand that abc12 is a string. Normally it would be interpreted as a variable.

    As other users mentioned including the single quotes would produce the desired query, but the recommended way to assign parameter values is this:

      String hql = "FROM com.pck.Person where userId = :id"
      query.setParameter("id", userId);