[英]java.lang.ClassCastException: org.hibernate.internal.QueryImpl cannot be cast to com.models.User
I have a user table structured this way 我有这样构造的用户表
id name email
1 cc cc@yahoo.com
2 rr rr@yahoo.com
3 cc cc@yahoo.com
I am writing a query to save a log when ever it finds an email matching any of the row with the below hql 我正在写一个查询来保存日志,只要它找到匹配以下hql的任何行的电子邮件
String hql = "FROM User c WHERE c.email = :email order by c.id";
return (User) _sessionFactory.getCurrentSession().createQuery(hql).setParameter("email", email);
When I run my code I get this error 当我运行代码时,出现此错误
java.lang.ClassCastException: org.hibernate.internal.QueryImpl cannot be cast to com.models.User
at com.models.UserDao.getByEmail(UserDao.java:62)
You forgot to call uniqueResult()
to get the first result, the code should rather be: 您忘记了调用uniqueResult()
以获得第一个结果,该代码应该是:
return (User) _sessionFactory.getCurrentSession().createQuery(hql)
.setParameter("email", email)
.uniqueResult();
Indeed you get this error because you try to cast a Query
instance into a User
which cannot be done, you need to execute the query first to get your User
instance. 的确,您会收到此错误,因为您尝试将Query
实例强制转换为User
实例而无法完成,因此需要首先执行查询以获取User
实例。
If you want to get several results then consider using list()
, the code will then be something like: 如果要获得多个结果,请考虑使用list()
,代码如下所示:
return (List<User>) _sessionFactory.getCurrentSession().createQuery(hql)
.setParameter("email", email)
.list();
It seems that you forgot to call the getResultList()
method at the end. 看来您忘了最后调用getResultList()
方法。
return (List<User>) _sessionFactory.getCurrentSession().createQuery(hql)
.setParameter("email", email)
.getResultList();
You should notice that since you are expecting more than one result, you'll need to change this command a bit or adapt the code to where this is returning to. 您应该注意到,由于期望得到不止一个结果,因此需要稍微更改此命令或使代码适应返回的位置。
You have to extract your result out of Query. 您必须从Query中提取结果。 You can extract a single Object by using 您可以使用提取单个对象
.createQuery(hql).getSingleResult();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.