【问题标题】:JPA Hibernate bulk/batch update in Spring MVCSpring MVC 中的 JPA Hibernate 批量/批量更新
【发布时间】:2013-07-11 15:32:58
【问题描述】:

我是 Spring MVC 的新手,对 JPA 也不太了解。我要做的就是更新记录列表,并且当我遍历列表并在 DAO 上调用更新时它运行良好。

但我不想执行 100 次更新/插入操作或数据库往返。

谁能告诉我如何通过批量更新而不是执行以下操作来更新大约 100 条记录:

Controller:
    List<MyEntity> list = form.getList();
    for(MyEntity e : list){
        dao.update(e);
    }

Dao:
    public T update(T entity){
         entityManager.merge(entity);        
    }

是否有可能,如果有人可以为我提供一种执行批量更新的简单方法。如果我能得到尽可能多的解释,我将不胜感激。

谢谢

【问题讨论】:

    标签: hibernate spring-mvc jpa jpa-2.0 spring-data-jpa


    【解决方案1】:

    您所拥有的几乎是通过 JPA 更新多行的标准方法。暴露save(Iterable&lt;T&gt; items) 的事件spring-data-jpa 只是在Iterator 上循环。 here 的另一个问题在选项上得到了很好的回答,但简而言之,您走在正确的道路上,而另一种选择是自己制定和执行更新语句。

    更新: 在单个事务中执行可能会提高性能,因为您只有一次事务开销。您还会遇到这样的情况,如果其中一个更新失败,任何以前的更新也会回滚。 (因此,您可能会丢失以前更新中的所有“工作”——您可能想要也可能不想要)

    另外,请注意您正在使用的事务管理器类型(例如 JTA 或 JPA)和 JPA 实现(例如 Hibernate),因为有时它们不能很好地结合使用。

    所以,在你的 DAO 代码中你可能想要这样做;

    • 添加重载update(Iterator&lt;Entity&gt; entities) 代码
    • 在该代码中执行以下操作;

      entityManager.getTransaction().begin();//start the transaction

      for (Entity entity : entities) {

          entityManager.merge(entity);//update an entity
      

      }

      entityManager.getTransaction().commit();//complete the transaction

    • 或者你可以在你的save(Iterable&lt;Entity&gt; entities)方法上使用@Transactional注解。确保你在 Spring Context 中也有事务注释支持

    【讨论】:

    • 如果我在事务中执行循环并最终调用提交怎么办。会有什么不同。你能解释一下吗
    • 回答Spring-Batch部分,需要对调用者做同步响应吗?
    • 在这种情况下(同步)spring-batch 可能不是最佳选择,因为它主要面向异步处理和响应。
    猜你喜欢
    • 1970-01-01
    • 2021-08-13
    • 2011-02-15
    • 1970-01-01
    • 2012-02-16
    • 2011-07-07
    • 2011-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多