Spring Jpa ManyToMany (many) relationship cascade = {CascadeType.X} configuration and summary

Roles table

Here Insert Picture Description

user table

Here Insert Picture Description

Middle of the table

Here Insert Picture Description

CascadeType.MERGE

New account and add the role does not exist, the statement Jpa executed
can be seen first on the role of the character table query, add a role does not exist.

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

Is that when we delete the user will cascade deletes the corresponding role in the above table, if I delete a user 李欣1, the corresponding character guestwill be deleted.
So will there is a problem, if it is a 王五user, its role is guest, because the middle of the table there is 王五->guesta relationship, so the program will error.


CascadeType.PERSIST

New users and add roles that do not exist, the statement Jpa execution
can still see the first query according to Id, does not exist on the error, it does not perform an operation to add, if there is added successfully

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=?

important point:

  • When CascadeType.PERSIST CascadeType.MERGE and are accompanied by, cascade = {CascadeType.PERSIST, CascadeType.MERGE}said the Internet that will only appear if the role exists, will be reported to the role of abnormal repeatjava.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'admin' for key 'UK_iubw515ff0ugtm28p8g3myt0h'
  • In ManyToManylightly Do not use this to cascade in cascade = CascadeType.REMOVE
  • In ManyToManyDo not cascade in = {CascadeType.PERSIST, CascadeType.MERGE}, so that the two simultaneous
  • In ManyToManyNever use cascade = CascadeType.ALL
  • Recommended that a single cascade = {CascadeType.MERGE}can

It took about seven hours, summarize these things, I hope useful to you

Published 141 original articles · won praise 131 · views 210 000 +

Guess you like

Origin blog.csdn.net/qq_41621362/article/details/103951135