I'm handling a problem in downcasting a query.uniqueResult() using hibernate. I have 2 classes: - UserBean - UserLogin
In the first one I have the mapping of all my table fields as well as all the methods to deal with data. The second one, instead, represents only some user data that will be stored in the user session.
At certain point in my login method, I execute the query and I get 1 row (I already checked if the query is really returning some result). The point is that I cannot downcast from Object type (that is the query.uniqueResult() type) to the UserLogin type.
Does someone know which could be the problem?
Thanks a lot!
This is the login method:
public UserLogin login(String email, String password){
Session session = iniHibernate();
UserLogin userLogin = null;
try{
session.beginTransaction();
Query query = session.createQuery("select email, name from "
+ "UserBean u where u.email = :user_email and "
+ "u.password = :user_password");
query.setString("user_email", email);
query.setString("user_password",password);
userLogin = (UserLogin) query.uniqueResult();
session.getTransaction().commit();
}catch (Exception e){
System.out.println(e);
}
return userLogin;
}
I have resolved it by adding entity type to the query object as:
This will work perfectly no need to worry for this problem.
According to the documentation of Query.uniqueResults:
The reason why it doesn't work is because your returning an array of Strings not the
UserBean
which I assume is mapped toUserLogin
.Try doing this:
or changing your query to get the object:
That should get you started.