steven35
steven35

Reputation: 4017

How to update a List of entities in Hibernate

I have a list of objects I'm trying to update in the database. I can update one of them like so

MyObj entity = getObjectFromDb();
entity.changeSomething();
getHibernateTemplate().update(entity);

What if I have a List of objects? Is it possible to do this without iterating through the list of objects and updating them one by one? That doesn't sound efficient to me. So I need something like this

List<MyObj> entities = getObjectsFromDb();
//change some attribute of the entities
getHibernateTemplate().update(entities); //this doesn't work because entities is a List

Upvotes: 2

Views: 16173

Answers (1)

Jarred Olson
Jarred Olson

Reputation: 3243

I'm unaware of a hibernate specific method that would take multiple objects (that doesn't mean it doesn't exist). EDIT -> Updating a collection does exist! I would imagine that it is simply iterating through them one by one and executing 1 query per object. A few options for you would be (in order of what I think would be best/most performant):

  • You could write a Bulk HQL Update update statement.
  • You could write a raw SQL update statement.
  • You could write your own helper object that takes multiple objects and saves them
  • You could rely on Hibernate's dirty/flush logic to save the objects that have changed and developers for all of time will curse you.

Upvotes: 2

Related Questions