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.
We can update an object in hibernate by calling the update() method, provided by the org. hibernate. Session. Though the update() method is used to update an object, there are two different ways to use update() method.
Syntax: UPDATE table_name SET column_name1 = new_value1, column_name2 = new_value2 ---- WHERE condition; Here table_name is the name of the table, column_name is the column whose value you want to update, new_value is the updated value, WHERE is used to filter for specific data.
The basic SQL UPDATE syntax comes down to using keyword UPDATE followed by the name of our object (table or table alias) and the SET column name equals to some values. The FROM clause will come into play when we do joins and we can also have a WHERE clause when we need to update only a portion of data in a table.
You have just created a query, but you haven't executed it:
SQLQuery sqlQuery = session.createSQLQuery(query);
sqlQuery.executeUpdate();
Note that
'
-
User u = session.get(User.class, userName);
u.setPassword(newPassword);
You just forgot the execute method, them:
String query = "UPDATE users SET Password = '"+ newPassword +"' WHERE Username = '"+ login.getUsername() + "'";
try {
s.getTransaction().begin();
s.createSQLQuery(query).executeUpdate();
s.getTransaction().commit();
s.close();
}
catch (HibernateException erro){
s.getTransaction().rollback();
s.close();
}
I strongly advise you not to use concatenating parameters in order to prevent SQL injection attacks, or simply errors that depends of your Strings. Take a look at HQL and Criteria.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With