I'm handling a problem开发者_Go百科 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:
Query query = session.createQuery(queryString).addEntity(Foo.class);
Foo foo = query.uniqueResult();
This will work perfectly no need to worry for this problem.
According to the documentation of Query.uniqueResults:
Convenience method to return a single instance that matches the query, or null if the query returns no results.
The reason why it doesn't work is because your returning an array of Strings not the UserBean
which I assume is mapped to UserLogin
.
Try doing this:
(String[])query.uniqueResult();
or changing your query to get the object:
Query query = session.createQuery("select u from "
+ "UserBean u where u.email = :user_email and "
+ "u.password = :user_password");
That should get you started.
If you don't have Entity, you can use
Query query = session.createQuery(queryString);
Object[] obj= query.uniqueResult();
This works well for me.
精彩评论