简体   繁体   中英

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 wrt 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 wrt userId passed.

What changes do I need to do?

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

Looks like you are missing single quotes around userid.

Try with "FROM com.pck.Person where userId = '" + userId + "'";

or

Use named parameters with query.setParameter("userid", userId);

Posting the full stacktrace would help if this doesn't solve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM