Reputation: 3
Recently in an interview I was asked what is optimized way of updating a column instead of complete table. For eg- If I have a user table and the table has a column status, now if want to update the status column only not the complete table. Then what is the optimized way in hibernate to do this job.
Upvotes: 0
Views: 50
Reputation: 691655
Using an update query, just as you would do with SQL. Example from the documentation:
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 = s.createQuery( hqlUpdate )
.setString( "newName", newName )
.setString( "oldName", oldName )
.executeUpdate();
This should be used with care though, because it bypasses the first-level cache. That means that entities updates by this query that are already loaded in the session will not be aware of the update, and will still have the old name.
Hibernate can also be configured to only update the fields that have changed since the entity was loaded, but this is usually counter-productive.
Upvotes: 2