Reputation:
If I delete an entity in hybernate, when will the actual corresponding DELETE sql query be executed? Can I somehow delay it? Is there any possibility to do these deletions somehow cascaded, in groups? For example, with a query like DELETE FROM table WHERE id IN (34, 56, ...).
I use postgresql, if it counts (although I am looking for mainly a hybernate-centric and not postgresql-centric solution).
I need that primarily NOT for speed optimization.
Upvotes: 2
Views: 602
Reputation: 1912
Usually who decides it is the provider, but you can manipulate that decision a little.
Any kind of database update/insert/delete will be sent to the database if you flush the transaction or when the entityManager transaction is commited(), e.g. entityManager.flush()
or entityManager.getTransaction().commit()
.
Imagine now the following actions:
delete from uaiEntity uai where uai.id = 15 //customer01 invokes the delete but the transactions has not been flushed yet
select uai from uaiEntity uai // customer02 requires all uaiEntities...
Will the provider include the customer with id=15?
Because of the scenario above the provider can choose to invoke flush() or not.
You could set the FlushMode in the Query or in the Entitymanager.
With entityManager.setFlushMode(FlushModeType.COMMIT)
you will make sure that the provider will not flush until the commit time. The JPA Spec says:
When queries are executed within a transaction, if FlushModeType.AUTO is set on the Query or TypedQuery object, or if the flush mode setting for the persistence context is AUTO (the default) and a flush mode setting has not been specified for the Query or TypedQuery object, the persistence provider is responsible for ensuring that all updates to the state of all entities in the persistence context which could potentially affect the result of the query are visible to the processing of the query. The persistence provider implementation may achieve this by flushing those entities to the database or by some other means. If FlushModeType.COMMIT is set, the effect of updates made to entities in the persistence context upon queries is unspecified.
You could execute a JPQL like delete from uaiEntity where id in (:idList)
without a problem but make sure that your FlushModeType
is set to COMMIT
.
Upvotes: 2