Spring JpaRepostory delete vs deleteInBatch

后端 未结 3 655
你的背包
你的背包 2021-02-05 04:03

What is the difference between delete(...) and deleteInBatch(...) methods in JpaRepostory in Spring ? The second one \"deletes items in one SQL stateme

相关标签:
3条回答
  • 2021-02-05 04:42

    deleteInBatch(...) in the log would look like this: DELETE FROM table_name WHERE (((((((? = id) OR (? = id)) OR (? = id)) OR (? = id)) OR (? = id)) OR (? = id)) OR (? = id))

    That might leads to a problem if there are a large amount of data to be deleted, which reaches maximum size of the SQL server query: Maximum size for a SQL Server Query? IN clause? Is there a Better Approach

    0 讨论(0)
  • 2021-02-05 04:45

    The delete method is going to delete your entity in one operation. The deleteInBatch is going to batch several delete-statements and delete them as 1 operation.

    If you need a lot of delete operations the batch-deletion might be faster.

    0 讨论(0)
  • 2021-02-05 04:56

    The answers here are not complete!

    First off, let's check the documentation!

    void deleteInBatch(Iterable<T> entities)
    Deletes the given entities in a batch which means it will create a single Query.
    

    So the "delete[All]InBatch" methods will use a JPA Batch delete, like "DELETE FROM table [WHERE ...]". That may be WAY more efficient, but it has some caveats:

    • This will not call any JPA/Hibernate lifecycle hooks you might have (@PreDelete)
    • It will NOT CASCADE to other entities
    • You have to clear your persistence context or just assume it is invalidated.

    That's because JPA will issue a bulk DELETE statement to the database, bypassing the cache etc. and thus can't know which entities were affected.

    See Hibernate Docs

    The actual code where in Spring Data JPA

    And while I can't find a specific article here, I'd recommend everything Vlad Mihalcea has written, to gain a deeper understanding of JPA.

    TLDR: The "inBatch" methods use bulk DELETE statements, which can be drastically faster, but have some caveats bc. they bypass the JPA cache. You should really know how they work and when to use them to benefit.

    0 讨论(0)
提交回复
热议问题