开发者

Hibernate exception -- could not execute update query

I have the following method, usi开发者_JS百科ng Hibernate, that's driving me nuts. It's not updating my database correctly, and I cannot see what the problem. Can anyone help me with this?

public boolean changePassword(String username, String password) {
    HttpServletRequest request = ServletActionContext.getRequest();
    SessionFactory sessionFactory = (SessionFactory) request.getSession()
            .getServletContext().getAttribute("sessionFactory");
    Session session = sessionFactory.openSession();

    try {
        request = ServletActionContext.getRequest();
        Query myQuery = session.createQuery("update Administrator "
                + "set password = " + password + " where username = "
                + username);
        if (myQuery.executeUpdate() == 1) {
            return true;
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

    return false;
}

Here is what I have in my console:

Hibernate: update login set password=password1 where username=frank
could not execute update query


Try using parametrized queries to solve this issue.

Query myQuery = session.createQuery("update Administrator "
                + "set password = :password where username = :username");

I think the code for setting parameters is

myQuery.setParameter("username", username);

myQuery.setParameter("password", password);


Shouldn't be the parameter values escaped? Also: why don't you use setParameter() instead of constructing the whole query by hand? It will do all the necessary escaping for you. The code could be then:

Query q = session.createQuery("update Administrator set password =\
                               :password where username = :username");
q.setParameter("password", password);
q.setParameter("username", username);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜