rogeliog
rogeliog

Reputation: 3692

Hibernate update not working

I am new with hibernate and I was trying to update a mapped object with the following code, but it does not update

factory = config.buildSessionFactory();
session = factory.getCurrentSession();
Transaction t = session.beginTransaction();
String hql = "UPDATE  "+tableName+" SET  "+columnName+" =  '"+columnValue+"' WHERE  id ="+id+";";
Query query=session.createSQLQuery(hql);
t.commit();

Am I missing something? It do not crash nor update the record.

NOTE: I am using Hibernate3 and Mysql

Upvotes: 0

Views: 5436

Answers (2)

Nitin Chhajer
Nitin Chhajer

Reputation: 2339

You need to use query.executeUpdate() to run the query.
Also it is suggested that you use parameters instead of inline arguments. For eg. if the columnName = O'Reilly then the whole query will go wrong. Also if it is a mapped object you can use HQL rather than SQL query

Instead you can use this

//entity is your hibernate entity obj
String hql = "UPDATE  " + entity.getClass().getName + " as entity SET entity." + fieldName  + "= :columnValue WHERE  entity = :entity";
Query query=session.createQuery(hql).setParameter("columnValue", columnValue).setParameter("entity", entity);
query.executeUpdate();

Notice that you don't need to use single quotes. setParameter handles it.

Upvotes: 3

tibtof
tibtof

Reputation: 7957

You're missing query.executeUpdate();

Also, if you're updating a mapped object I would recommend you to make the changes to the java object, and let Hibernate do the update for you. Or at least use a hql query, not a native one.

Make sure that your persistence.xml file has show_sql set to true and watch the log to see if the update is executed.

<property name="hibernate.show_sql" value="true"/>

Upvotes: 9

Related Questions