Hibernate supports two main ways to update table columns.
The first is natural, loading the object into session , changing it at runtime, discard (post) the changes back to the database. This is the standard ORM style.
The second is mainly focused on a very efficient SQL UPDATE statement . It is described here as:
reference doc:
... However, Hibernate provides methods for mass executing a SQL-style DML statement executed using the Hibernate query language ...
It does not provide an API for querying criteria, but it works with HQL == with our domain model.
We can create a WHERE clause on top of our mapped objects and request an update from only the few columns that we have selected. There are some restrictions (JOIN is not supported), but they can be solved by subqueries ...
This is a fragment of a doc document:
Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); String hqlUpdate = "update Customer c set c.name = :newName where c.name = :oldName"; // or String hqlUpdate = "update Customer set name = :newName where name = :oldName"; int updatedEntities = session.createQuery( hqlUpdate ) .setString( "newName", newName ) .setString( "oldName", oldName ) .executeUpdate(); tx.commit(); session.close();
Also check out this Q & Q: Hibernate upgrade with criteria
source share