user2511713
user2511713

Reputation: 555

Hibernate vs SQL:Best way to Update column of all rows in a table

I have a database table alert and am using Hibernate.I am using mySQL.

I want to update all columns of the database. The table name is alert where as the mapping class of the table is Alert.

Using SQLQUERY:

session.beginTransaction();
session.createSQLQuery("update alert set retryCount=3"); 
session.getTransaction().commit();
session.close();

is not working.

Using HQL using dynaming update attribute

Query query=session.createQuery("from Alert");
for(int i=0;i<query.list().size();i++){
   Alert alert=(Alert)query.list().get(i);
   alert.setretryCount(3);
   session.update(alert);
 }
session.getTransaction().commit();

is working

Though the second one is working I think it will take much more time than a normal sql query.Is it so?Whats the best way to update a set of columns of all rows while using hibernate.

Upvotes: 2

Views: 6378

Answers (1)

Pear
Pear

Reputation: 470


Hi ! Have you tried this ?

session.beginTransaction();
String queryString = "update Alert a set a.retryCount=3"
Query query = session.createQuery(queryString);
session.executeUpdate(query);
session.close();

This is on the hibernate official documentation. This is an HQL request using entities as objects and not as SQL tables. I think it's better to do it this way since you don't need to care about your database model.

Could you give us the displayed stacktrace for the non-working method ?

Upvotes: 3

Related Questions