Spring data jpa detached entity

前端 未结 1 1546
野的像风
野的像风 2020-12-16 08:25

I started to work on a Spring Boot application using Spring Data JPA to setup a ManyToMany relationship between users and roles.

This relationship is defined as foll

相关标签:
1条回答
  • 2020-12-16 08:55

    When you save your entity, Spring internally checks if the entity is new (I forget the exact mechanism), and issues either a persist (if new) or merge (if existing).

    Since you have defined your User to UserRole relationship with Cascade.ALL, any persists/merge from User will cascade to UserRole as well.

    Given how Spring implements a save, and the behavior of cascading above, here are some scenarios to consider:

    • if both User and UserRole are new - you'll get a persist action when saving User, and a cascading persist to UserRole, which works fine since UserRole is new.
    • if User is new but UserRole is existing - again you'll get a persist action when saving User, and a cascading persist to UserRole, which results in an error since UserRole already exists!

    If you can guarantee that any UserRole you add to the relationship with User always exists, you could simply remove Cascade.Persist from your cascade options. Otherwise, I believe you'll have to use merge -- via custom repository and entityManager -- when saving your User in both scenarios above.

    Regarding your use of Cascade.ALL, which in this situation probably doesn't make sense, since you've got a @ManyToMany relationship, cascading ALL from User to UserRole may have some undesired effects (e.g. Cascade.Remove would remove UserRole every time a User is removed).

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