简体   繁体   English

无法使用HQL在Hibernate中获取结果集

[英]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. 我正在使用HQL触发查询,通常它应该返回空结果集,因为它没有任何记录。 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. 我期望列表大小为0,因为没有传递给userId的记录。

What changes do I need to do? 我需要做什么改变?

Lets say the value of userId was "abc12" 假设userId的值为“ abc12”

Given your code, the value of the string called hql would become: "FROM com.pck.Person where userId = abc12" 给定您的代码,名为hql的字符串的值将变为:“ FROM com.pck.Person,其中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. 如果您使用该字符串的值并尝试在任何数据库上将其作为查询运行,那么大多数人将无法理解abc12是字符串。 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. 好像您在userid周围缺少单引号。

Try with "FROM com.pck.Person where userId = '" + userId + "'"; 尝试使用"FROM com.pck.Person where userId = '" + userId + "'";

or 要么

Use named parameters with query.setParameter("userid", userId); 将命名参数与query.setParameter("userid", userId);

Posting the full stacktrace would help if this doesn't solve. 如果无法解决问题,则发布完整的stacktrace将有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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