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

Not able to fetch resultset in Hibernate using HQL

我正在使用 HQL 触发查询,通常它应该 return 空结果集,因为它没有任何记录 w.r.t。但是,它抛出

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

我的密码是

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

我预计列表大小为 0,因为没有记录 w.r.t userId 已通过。

我需要做哪些改变?

假设 userId 的值为 "abc12"

根据您的代码,名为 hql 的字符串的值将变为: "FROM com.pck.Person where userId = abc12"

如果您获取该字符串的值并尝试 运行 它作为对任何数据库的查询,他们中的大多数人将无法理解 abc12 是一个字符串。通常它会被解释为一个变量。

正如其他用户提到的,包括单引号会产生所需的查询,但分配参数值的推荐方法是这样的:

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

您似乎缺少将用户 ID 括起来的单引号。

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

query.setParameter("userid", userId);

中使用命名参数

如果这不能解决,发布完整的堆栈跟踪信息会有所帮助。