iseunghan 2022. 8. 4. 14:05
๋ฐ˜์‘ํ˜•

CascadeType.DELETE, orphanRemoval ์ฐจ์ด์ 

 

๋ชฉํ‘œ

CASCADE.REMOVE ์™€ orphanRemoval์˜ ์ฐจ์ด์ ์— ๋Œ€ํ•ด์„œ ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

ํ…Œ์ŠคํŠธ์šฉ ์—”ํ‹ฐํ‹ฐ

public class Parent {
	@OneToMany(mappedBy = "parent")
    private List<Child> children = new ArrayList<>();
}

public class Child {
	@ManyToOne
    @JoinColumn(name = "PARENT_ID")
    private Parent parent; 
}

CASCADE.REMOVE

@OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE)
private List<Child> children = new ArrayList<>();
  • ์ƒํ™ฉ 1. children.remove(child)
    • ์ด๋•Œ, child๋Š” DETACH ์ƒํƒœ๊ฐ€ ๋œ๋‹ค. ์ฆ‰, ๊ณ ์•„๊ฐ€ ๋œ๋‹ค. (๋ถ€๋ชจ๊ฐ€ ์—†์ด ์—ฌ์ „ํžˆ DB์— ๋‚จ์•„์žˆ๋‹ค.)
  • ์ƒํ™ฉ 2. parentRepository.delete(parent)
    • ์ด๋•Œ, parent์— ์†ํ•œ ๋ชจ๋“  child๋Š” ํ•จ๊ป˜ ์‚ญ์ œ๋œ๋‹ค.

orphanRemoval = true

@OneToMany(mappedBy = "parent", orphanRemoval = true)
private List<Child> children = new ArrayList<>();
  • ์ƒํ™ฉ 1. children.remove(child)
    • ์ด๋•Œ ๋ฆฌ์ŠคํŠธ์—์„œ ์ œ๊ฑฐ๋œ child๋ฅผ ๊ณ ์•„๋ผ๊ณ  ์ธ์‹ํ•˜๊ณ  DB์—์„œ ์ œ๊ฑฐํ•œ๋‹ค.
  • ์ƒํ™ฉ 2. parentRepository.delete(parent)
    • ์ด๋•Œ, parent์— ์†ํ•œ ๋ชจ๋“  child๋Š” ํ•จ๊ป˜ ์‚ญ์ œ๋œ๋‹ค.

์ฐจ์ด์ 

  • ๊ณตํ†ต
    • ๋ถ€๋ชจ๋ฅผ ์‚ญ์ œํ•˜๋ฉด ์ž์‹๋„ ํ•จ๊ป˜ ์‚ญ์ œ
  • CASCADE.REMOVE
    • ์ž์‹์„ ๋ฆฌ์ŠคํŠธ์—์„œ ์ œ๊ฑฐํ•˜๋ฉด DB์—์„œ ์ œ๊ฑฐ ์•ˆ์‹œํ‚ด.
  • orphanRemoval
    • ์ž์‹์„ ๋ฆฌ์ŠคํŠธ์—์„œ ์ œ๊ฑฐํ•˜๋ฉด DB์—์„œ๋„ ์ œ๊ฑฐํ•จ.

 

 

๋ฐ˜์‘ํ˜•