角色表
用戶表
中間表
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個小時,總結這些東西,希望對你有用