Should I let JPA or the database cascade deletions?

前端 未结 3 1714
眼角桃花
眼角桃花 2021-02-05 19:23

Let\'s say we have two entities, A and B. B has a many-to-one relationship to A like follows:

@Entity
public class A {
  @OneToMany(mappedBy="a_id")
  p         


        
相关标签:
3条回答
  • 2021-02-05 19:50

    In EclipseLink you can use both if you use the @CascadeOnDelete annotation. EclipseLink will also generate the cascade DDL for you.

    See, http://wiki.eclipse.org/EclipseLink/Examples/JPA/DeleteCascade

    This optimizes the deletion by letting the database do it, but also maintains the cache and the persistence unit by removing the objects.

    Note that orphanRemoval=true will also delete objects removed from the collection, which the database cascade constraint will not do for you, so having the rules in JPA is still necessary. There are also some relationships that the database cannot handle deletion for, as the database can only cascade in the inverse direction of the constraint, a OneToOne with a foreign key, or a OneToMany with a join table cannot be cascaded on the database.

    0 讨论(0)
  • 2021-02-05 19:52

    This answer raises some really strong arguments about why it should be JPA that handles the cascade, not the database.

    Here's the relevant quote:

    ...if you would make cascades on database, and not declare them in Hibernate (for performance issues) you could in some circumstances get errors. This is because Hibernate stores entities in its session cache, so it would not know about database deleting something in cascade.

    When you use second-level cache, your situation is even worse, because this cache lives longer than session and such changes on db-side will be invisible to other sessions as long old values are stored in this cache.

    0 讨论(0)
  • 2021-02-05 20:06

    I'd prefer the database. Why?

    • The database is probably a lot faster doing this
    • The database should be the primary place to hold integrity and relationship information. JPA is just reflecting that information
    • If you're connecting with a different application / platform (i.e. without JPA), you can still cascadingly delete your records, which helps increase data integrity
    0 讨论(0)
提交回复
热议问题