【问题标题】:Bulk update from object list in Java using JPA使用 JPA 从 Java 中的对象列表批量更新
【发布时间】:2022-01-05 04:03:14
【问题描述】:

我正在尝试使用 JPA 进行多次更新。我现在的情况,可能是使用 JPA 更新同一实体中的多个列记录。我试图避免在循环中使用更新语句,但我找不到任何相关信息。

我使用entity manager 来执行查询

@Override
    public void updateAllNotes(List<Note> NOTES) {
        LocalTime now = LocalTime.now(ZoneId.of("America/Mexico_City"));
        String query = "UPDATE Note SET TITLE = :title, CONTENT = :content, UPDATED_AT = :updatedAt WHERE ID = :id";

        /* I'm trying to avoid this */
        for (Note note:NOTES) {
            entityManager.createQuery(query)
                    .setParameter("title", note.getTitle())
                    .setParameter("content", note.getContent())
                    .setParameter("updatedAt", now)
                    .setParameter("id", note.getId())
                    .executeUpdate();
        }
    }

【问题讨论】:

标签: java jpa entitymanager


【解决方案1】:

您可以尝试下面的代码可能会有所帮助,或者您可以参考JPA - Batch/Bulk Update - What is the better approach?

 public void updateAllNotes(List<Note> NOTES) {
    LocalTime now = LocalTime.now(ZoneId.of("America/Mexico_City"));
    List<Integer> idList = NOTES.stream().map(Note::getId).collect(Collectors.toList());
    String query = "UPDATE Note SET TITLE = (?1), CONTENT = (?2), UPDATED_AT = (?3) WHERE ID = (?4)";


        entityManager.createQuery(query)
                .setParameter(1, note.getTitle())
                .setParameter(2, note.getContent())
                .setParameter(3, now)
                .setParameter(4, idList)
                .executeUpdate();
    }

【讨论】:

  • 我能知道将 id 列在列表中的原因吗?
  • 对不起.. 创建 idList 后,您可以删除 for 循环。我已经更新了。我认为它现在应该可以工作了。
  • @EmilianoVazquezBanda 要编辑多行,使用的 id 列表,因此您不必更新循环中的每一行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-13
  • 2013-07-11
  • 2016-11-18
  • 2011-07-07
  • 2021-03-14
  • 1970-01-01
  • 2012-11-22
相关资源
最近更新 更多