Search
Duplicate
โ˜•

cascade.remove vs orphan removal

cascade

โ†’ ๋ถ€๋ชจ ์—”ํ„ฐํ‹ฐ์˜ ๋ณ€๊ฒฝ์ด ์ž์‹ ์—”ํ„ฐํ‹ฐ์—๊ฒŒ ์˜ํ–ฅ์„ ์ค€๋‹ค.
ex) team, member ์‹œ team ์„ ์ƒ์„ฑํ•˜๊ฑฐ๋‚˜ team ์„ ์‚ญ์ œํ•  ๋•Œ member ๋„ ๊ฐ™์ด ์ƒ์„ฑ๋˜๊ณ  ์‚ญ์ œ๋œ๋‹ค.

orphan removal

โ†’ ๋ถ€๋ชจ ๊ฐ์ฒด์˜ ์ž์‹ ๋ณ€์ˆ˜์—์„œ ์ž์‹ ๊ฐ์ฒด๊ฐ€ ์‚ญ์ œ ๋˜์—ˆ์„ ๋•Œ ์ž์‹ ์—”ํ„ฐํ‹ฐ๋ฅผ ์‚ญ์ œํ•˜๋Š” ๊ฒƒ
ex) team, member ์‹œ team ์˜ members ์—์„œ member ์›์†Œ ํ•˜๋‚˜๊ฐ€ ์‚ญ์ œ๋˜์—ˆ์„ ๋•Œ ํ•ด๋‹น ์—”ํ„ฐํ‹ฐ๊ฐ€ ์—ฐ๊ด€์—์„œ ์‚ญ์ œ๋œ๋‹ค.
์ฃผ์˜์ : hibernate5.6 ๊ธฐ์ค€ orphan removal ์€ cascade ์˜ ์†์„ฑ์— ์˜ํ–ฅ์„ ๋ฐ›๋Š”๋‹ค. cascade ๊ฐ€ persist ์ด๊ฑฐ๋‚˜ all ์ผ๋•Œ๋งŒ ์œ ํšจํ•˜๋‹ค.

์˜ˆ์‹œ

ํ™˜๊ฒฝ

โ€ข
Team, Member ๋Š” OneToMany ๋‹จ๋ฐฉํ–ฅ

cascade ๊ฐ€ remove ์ผ ๋•Œ

entityManager.getTransaction().begin(); Team morak = entityManager.find(Team.class, 1); entityManager.remove(morak); entityManager.getTransaction().commit();
Java
๋ณต์‚ฌ
โ†’ team ์„ ์‚ญ์ œํ•˜๋ฉด member ๋„ ์‚ญ์ œ๋œ๋‹ค. ๋ฌผ๋ก  ์ œ์•ฝ์กฐ๊ฑด์— ์˜ํ•ด member๊ฐ€ ๋จผ์ € ์‚ญ์ œ๋œ๋‹ค.

cascade ๊ฐ€ persist ์ด๊ณ  orphan removal ์ผ ๋•Œ

entityManager.getTransaction().begin(); entityManager.persist(morak); morak.removeMember(0); entityManager.getTransaction().commit();
Java
๋ณต์‚ฌ
๊ฒฐ๊ณผ
Hibernate: insert into team (id, name) values (default, ?) Hibernate: insert into member (id, name, team_id) values (default, ?, ?) Hibernate: delete from member where id=?
Java
๋ณต์‚ฌ
orphan removal ์ด ์ž˜ ๋™์ž‘ํ•œ๋‹ค.

๊ฒฐ๋ก 

โ€ข
cascade remove ๋Š” team ์ด ์‚ญ์ œ๋  ๋•Œ์˜ ์ƒํ™ฉ
โ€ข
orphan removal ์€ team ์˜ members ์—์„œ member ๊ฐ€ ์‚ญ์ œ๋  ๋•Œ์˜ ์ƒํ™ฉ

๋ฒˆ์™ธ

cascade ๊ฐ€ persist ์ด๊ณ  orphan removal=false(default) ์ผ ๋•Œ ๋ถ€๋ชจ ์—”ํ„ฐํ‹ฐ๋ฅผ ์‚ญ์ œํ•˜๋ฉด

JdbcSQLIntegrityConstraintViolationException โ†’ ์ œ์•ฝ์กฐ๊ฑด ์—๋Ÿฌ

cascade ๊ฐ€ persist ์ด๊ณ  orphan removal=true ์ผ ๋•Œ ๋ถ€๋ชจ ์—”ํ„ฐํ‹ฐ๋ฅผ ์‚ญ์ œํ•˜๋ฉด

entityManager.getTransaction().begin(); entityManager.persist(morak); entityManager.remove(morak); entityManager.getTransaction().commit();
Java
๋ณต์‚ฌ
Hibernate: insert into team (id, name) values (default, ?) Hibernate: insert into member (id, name, team_id) values (default, ?, ?) Hibernate: delete from member where id=? Hibernate: delete from team where id=?
Java
๋ณต์‚ฌ
orphan removal ์˜ต์…˜์— ์˜ํ•ด cascade remove ์ฒ˜๋Ÿผ ๋™์ž‘