下降hibernate查询的问题 [英] Problems downcasting a hibernate query

查看:90
本文介绍了下降hibernate查询的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用hibernate向下转换query.uniqueResult()时遇到了一个问题。我有2个类:
- UserBean
- UserLogin

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.

在我的登录方法中,我执行查询,并得到1行(我已经检查过查询是否真的返回了一些结果)。重点是我不能从Object类型(即query.uniqueResult()类型)向UserLogin类型下注。

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?

非常感谢!

这是登录方法:

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;
}


推荐答案

a href =http://docs.jboss.org/hibernate/core/3.2/api/org/hibernate/Query.html#uniqueResult%28%29 =nofollow> Query.uniqueResults :
$ b

According to the documentation of Query.uniqueResults:


便捷方法返回与查询匹配的单个
实例,或者如果查询返回无结果,则返回
null 。

Convenience method to return a single instance that matches the query, or null if the query returns no results.

它不起作用的原因是因为你返回一个字符串数组而不是 UserBean 我假设它映射到 UserLogin

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.

尝试这样做:

(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");

这应该让你开始。

这篇关于下降hibernate查询的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆