0

I'm trying to do a multiple update using JPA. What I currently now, It's that is possibly to update multiple columns records in a same entity using JPA. I'm trying to avoid using update statements in loop but I couldn't find any information about this.

I'm using an entity manager in order to execute the queries

@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();
        }
    }

1 Answers1

0

You can try below code may be it helpful or you can refer 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();
    }
Dhaval Goti
  • 447
  • 2
  • 10
  • 25