尝试使用WHERE子句时获取异常

时间:2014-04-27 11:25:29

标签: java hibernate hql

尝试使用where子句执行查询时,出现异常:

SEVERE: Unknown column 'suhail03' in 'where clause'
org.hibernate.exception.SQLGrammarException: could not execute query
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
    at org.hibernate.loader.Loader.doList(Loader.java:2223)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2104)
    at org.hibernate.loader.Loader.list(Loader.java:2099)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:378)
            ...

此处suhail03where子句中的条件。我哪里错了?

 private boolean appAuthorized(String username) {

    boolean hasAuthorized = false;
    try {
        Session session = new HVR().getSession();

        String hql = "from UCred where username =" + username; // WHERE QUERY

        List list = session.createQuery(hql).list();
        Iterator iterator = list.iterator();
        while(iterator.hasNext()) {
            UCred user = (UCred)iterator.next();
            if(user.getAccessToken().compareTo("null") == 0) {
                hasAuthorized = false;
            }else {
                hasAuthorized = true;
            }
        }
    }catch(Exception exc) {
        exc.printStackTrace();
        return false;
    }
    return hasAuthorized;

}

1 个答案:

答案 0 :(得分:1)

如果没有参数绑定,则必须将参数String连接起来(错误代码):

String hql = "from UCred where username =" + "'" + username + "'";

使用位置参数

更好
String hql = "from UCred ucred where ucred.username = :username";

List list = session.createQuery(hql).
            .setParameter("username", username)
             .list();