0

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

2 Answers 2

9

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"/>
Sign up to request clarification or add additional context in comments.

1 Comment

query.execute() gives me an error on Eclipse, I can only use query.executeUpdate(), but it does not work
3

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.

2 Comments

if it's a hql query instead of columnName he should use the name of the field that is mapped to that column. also, .setParameter("entity", entity) should be replaced with .setParameter("entity", id);
@tibtof Thanks for the columnName clarification, and you can use entity as is. It is mandatory for each hibernate mapping to give an id field in the mapping. This will be resolved at the run time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.