Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update cell Data using Hibernate SQL query

Tags:

sql

hibernate

hql

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.

like image 790
Androider Avatar asked Jun 08 '12 12:06

Androider


People also ask

How do you update a record in hibernate?

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.

How do you update an entire row in SQL?

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.

How do you update an object in SQL?

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.


2 Answers

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);
like image 137
JB Nizet Avatar answered Oct 12 '22 23:10

JB Nizet


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.

like image 36
Marcelo Machado Avatar answered Oct 13 '22 01:10

Marcelo Machado