Spring Jpa ManyToMany(多對多)關係中的cascade={CascadeType.X} 的配置與總結

角色表

在這裏插入圖片描述

用戶表

在這裏插入圖片描述

中間表

在這裏插入圖片描述

CascadeType.MERGE

新增賬戶並添加不存在的角色,Jpa執行的語句
可以看到首先對role角色表進行了查詢,不存在就添加一個角色。

Hibernate: select role0_.role_id as role_id1_4_0_, role0_.role_name as role_nam2_4_0_ from role role0_ where role0_.role_id=?
Hibernate: insert into user (user_name, user_password, user_id) values (?, ?, ?)
Hibernate: insert into role (role_name) values (?)

CascadeType.REMOVE

就是當我們對用戶進行刪除時,也會級聯的刪除其對應的角色,如上表,如果我刪除用戶李欣1時,其對應的角色guest也會刪除。
那麼就會存在一個問題,如果還一個王五的用戶,其角色也是guest,由於中間表中還存在王五->guest的關係,所以程序就會報錯。


CascadeType.PERSIST

新增用戶並添加不存在的角色,Jpa執行的語句
可以看到還是先根據Id進行查詢,不存在就報錯,不會在執行添加的操作了,如果存在添加成功

Hibernate: select user0_.user_id as user_id1_6_1_, user0_.user_name as user_nam2_6_1_, user0_.user_password as user_pas3_6_1_, user0_.user_status as user_sta4_6_1_, userinfo1_.info_id as info_id1_8_0_, userinfo1_.phone as phone2_8_0_, userinfo1_.email as email3_8_0_, userinfo1_.age as age4_8_0_, userinfo1_.birth as birth5_8_0_, userinfo1_.address as address6_8_0_, userinfo1_.school as school7_8_0_, userinfo1_.edu_back as edu_back8_8_0_, userinfo1_.user_major as user_maj9_8_0_, userinfo1_.info_user_id as info_us10_8_0_ from user user0_ left outer join user_info userinfo1_ on user0_.user_id=userinfo1_.info_user_id where user0_.user_id=?
Hibernate: select role0_.role_id as role_id1_4_0_, role0_.role_name as role_nam2_4_0_ from role role0_ where role0_.role_id=?

注意點:

  • 當CascadeType.PERSIST和CascadeType.MERGE都配上時,cascade = {CascadeType.PERSIST, CascadeType.MERGE}纔會出現網上所說的那種,如果角色存在,纔會報角色重複的異常 java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'admin' for key 'UK_iubw515ff0ugtm28p8g3myt0h'
  • ManyToMany中輕易不要使用cascade = CascadeType.REMOVE 這種級聯關係
  • ManyToMany中不要cascade = {CascadeType.PERSIST, CascadeType.MERGE},讓這兩個同時出現
  • ManyToMany絕對不要使用 cascade = CascadeType.ALL
  • 推薦單獨使用cascade = {CascadeType.MERGE}即可

花了大概7個小時,總結這些東西,希望對你有用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章