java 如何在 Hibernate 中更新实体列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29627913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:37:46  来源:igfitidea点击:

How to update a List of entities in Hibernate

javaspringhibernatesql-update

提问by steven35

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

回答by Jarred Olson

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):

我不知道会采用多个对象的休眠特定方法(这并不意味着它不存在)。编辑 ->更新集合确实存在!我想它只是一个一个地遍历它们并为每个对象执行 1 个查询。您的一些选择是(按照我认为最好/最高性能的顺序):

  • You could write a Bulk HQL Updateupdate 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.
  • 您可以编写批量 HQL 更新更新语句。
  • 您可以编写原始 SQL 更新语句。
  • 您可以编写自己的辅助对象来获取多个对象并保存它们
  • 您可以依靠 Hibernate 的脏/刷新逻辑来保存已更改的对象,而开发人员将一直诅咒您。