G
G
gsaw2021-02-02 09:01:58
Java
gsaw, 2021-02-02 09:01:58

[spring jpa repository] how to deleteInBatch correctly?

Hello, it is

necessary to delete records from the table and create new ones, new ones can have the same primary keys as the deleted ones. Deleted by foreign key.

If you do this, then JPA / hibernet first makes a request to the database, then deletes the records and performs a DELETE FROM for each. Which is not very optimal, since there can be a lot of records.

rep.deleteAllByForeignKey(forejgnKey);
inputList.forEach(newrec -> repo.save(newrec));


If I do this, then JPA first makes a query to the database, then one DELETE FROM deletes all records, but then stumbles on adding new records

repo.deleteInBatch(repo.findAllByForeignKey(foreignKey));
inputList.forEach(newrec -> repo.save(newrec));


The error comes out like this

org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)


Everything is done in one transaction, maybe you need to somehow tell hibernate that "the data is deleted, forget about it?"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
gsaw, 2021-02-02
@gsaw

As soon as I sent the question, it came to my mind to look at the documentation on deleteInBatch and it is written in black and white there.

Assume that we will clear the EntityManager after the call.

Generally em.clear() between deleteInBatch and save helped.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question