Search code examples
sqlhibernatehql

How to update cell Data using Hibernate SQL query


I have a table 'users', with many columns, among them two are 'Username' and 'Password' username is primary key column

I want to update password for a username. here is my code it is working fine (no error or exception) but not updating password.

I am new to Hibernate and do not know much of its syntax. please help me

 String query = "UPDATE users SET Password = '"+ newPassword +"' WHERE Username = '"+ login.getUsername() + "'";

 session.createSQLQuery(query);

login.getUsername() is getting required username correctly

Rest of code is working fine problem is in above code.


Solution

  • You have just created a query, but you haven't executed it:

    SQLQuery sqlQuery = session.createSQLQuery(query);
    sqlQuery.executeUpdate();
    

    Note that

    • you should use named parameters instead of concatenating parameters. This would prevent SQL injection attacks, or simply errors when the password or user name contains '
    • in Hibernate, you typically do such simple operations with:

    -

    User u = session.get(User.class, userName);
    u.setPassword(newPassword);