1

I have a user table structured this way

id    name     email
1     cc       [email protected]
2     rr       [email protected]
3     cc       [email protected]

I am writing a query to save a log when ever it finds an email matching any of the row with the below 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)
4
  • Do you expect one result? Or more than one? Commented Aug 8, 2016 at 18:16
  • more than one result Commented Aug 8, 2016 at 18:19
  • It seems that you are missing the .getResultList() at the end of your command. Commented Aug 8, 2016 at 18:20
  • @Francis so it makes no sense to cast it to a User object since the result will provide you with something else, you need to get the first result and then cast it to a user. Commented Aug 8, 2016 at 18:21

3 Answers 3

2

You forgot to call uniqueResult() to get the first result, the code should rather be:

 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.


If you want to get several results then consider using list(), the code will then be something like:

 return (List<User>) _sessionFactory.getCurrentSession().createQuery(hql)
    .setParameter("email", email)
    .list();
Sign up to request clarification or add additional context in comments.

2 Comments

what about if i want to get the third row
Yeah, that's why i asked if he needed one or more than one result. @NicolasFilotto
1

It seems that you forgot to call the getResultList() method at the end.

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.

Comments

0

You have to extract your result out of Query. You can extract a single Object by using

.createQuery(hql).getSingleResult();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.