Home ๐Ÿ” ๊ฒŒ์‹œ๋ฌผ ์‚ญ์ œ์‹œ ๋Œ“๊ธ€๋„ ํ•จ๊ป˜ ์‚ญ์ œ ๊ตฌํ˜„
Post
Cancel

๐Ÿ” ๊ฒŒ์‹œ๋ฌผ ์‚ญ์ œ์‹œ ๋Œ“๊ธ€๋„ ํ•จ๊ป˜ ์‚ญ์ œ ๊ตฌํ˜„



์‚ญ์ œ



์‚ญ์ œํ–ˆ๋‹ค๊ณ  ํ•ด์ฃผ๊ณ 
๋ณต๊ตฌ๋ฅผ ์œ„ํ•ด ๋ณด๊ด€ํ•ด ๋†“์•˜๋‹ค๊ฐ€
์ผ์ • ๊ธฐ๊ฐ„์ด ์ง€๋‚ฌ์„ ๊ฒฝ์šฐ์—๋Š” Cascade๋ฅผ ์‚ฌ์šฉํ•ด ์‚ญ์ œ



Cascade



์ƒ๋ช…์ฃผ๊ธฐ๋ฅผ ๊ณต์œ ํ•˜๋Š”(์–ด๋Š ํ•œ ์—”ํ‹ฐํ‹ฐ์˜ ์ƒ๋ช…์ฃผ๊ธฐ ์˜์กด) ์—”ํ‹ฐํ‹ฐ๋“ค์ด ์กด์žฌํ•  ๊ฒฝ์šฐ
Cascade๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ข‹๋‹ค.
๊ฒŒ์‹œํŒ์ด ์ œ๊ฑฐ๋จ๊ณผ ๋™์‹œ์—
๊ทธ ์•ˆ์— ์กด์žฌํ•˜๋Š” ๊ฒŒ์‹œ๊ธ€, ๋Œ“๊ธ€ (ํ˜น์€ ์ถ”์ฒœ)์ด ๋ชจ๋‘ ์ œ๊ฑฐ๋  ๊ฒƒ์ด๋‹ค.


๋‹จ๋ฐฉํ–ฅ ๋งคํ•‘์œผ๋กœ ์‚ฌ์šฉ์ด ๊ฐ€๋Šฅํ•  ๊ฒฝ์šฐ ์–‘๋ฐฉํ–ฅ ๋งคํ•‘์„ ์ „ํ˜€ ์‚ฌ์šฉํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค.


ํ•˜์ง€๋งŒ ์šฐ๋ฆฌ๊ฐ€ Cascade๋ฅผ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ
์ฆ‰ @ManyToOne ์–ด๋…ธํ…Œ์ด์…˜์˜ ํ‘œํ˜„์œผ๋กœ๋งŒ ์ถฉ๋ถ„ํžˆ ๋งคํ•‘์ด ๊ฐ€๋Šฅํ•œ๋ฐ๋„ ๋ถˆ๊ตฌํ•˜๊ณ 
@OneToMany ์–ด๋…ธํ…Œ์ด์…˜์„ ํ™œ์šฉํ•˜๊ณ  ๋ถˆํ•„์š”ํ•œ ์–‘๋ฐฉํ–ฅ ๋งคํ•‘์„ ์‚ฌ์šฉํ•˜๊ฒŒ ๋œ๋‹ค.


์˜ˆ๋ฅผ๋“ค์–ด ๋Œ“๊ธ€ ์•„๋ž˜์— ๋Œ€๋Œ“๊ธ€์„ ๋‹ฌ๊ณ  ์ด๋Ÿฌํ•œ ์‹์œผ๋กœ ๊ผฌ๋ฆฌ๋ฅผ ๋ฌด๋Š” ํ˜•์‹์„ ์ง€์นญํ•˜๋Š”๋ฐ
์ด๋Ÿฌํ•œ ๋ถ€๋ถ„์€ 1:N์˜ ๊ด€๊ณ„๋กœ ํ‘œํ˜„์ด ๊ฐ€๋Šฅํ•˜๋‹ค.
์ด๋Ÿฌํ•œ ๋ถ€๋ถ„์— ์žˆ์–ด์„œ๋Š” ์–‘๋ฐฉํ–ฅ ๋งคํ•‘์ด ํ•„์š”ํ•˜๋‹ค.


  • JPA์— ์˜ํ•ด ์ฒ˜๋ฆฌ๋˜์–ด JPA์— ์˜ํ•ด ์™ธ๋ž˜ ํ‚ค๋ฅผ ์ฐพ์•„๊ฐ€๋ฉฐ ์ฐธ์กฐํ•˜๋Š” ๋ ˆ์ฝ”๋“œ๋ฅผ ์ œ๊ฑฐ
  • ์—ฌ๋Ÿฌ๊ฐœ์˜ ์ฟผ๋ฆฌ์‚ฌ์šฉํ•ด ์ œ๊ฑฐ



@Delete



Cascade์™€ ๊ฐ™์€ ํšจ๊ณผ

1
@OnDelete(action = OnDeleteAction.CASCADE)


  • ๋ถˆํ•„์š”ํ•œ ์—ฐ๊ด€๊ด€๊ณ„ ๋งคํ•‘์„ ์ œ๊ฑฐํ•ด์ฃผ๊ณ  ์—ฐ๊ด€๊ด€๊ณ„๋ฅผ ์ œ๊ฑฐ
  • DB์— ์˜ํ•ด ์ง์ ‘ ์ฒ˜๋ฆฌ
  • ๋‹จ์ผ ์ฟผ๋ฆฌ๋ฅผ ํ†ตํ•ด ์—ฐ์‡„์ ์œผ๋กœ ์ œ๊ฑฐ



๊ตฌํ˜„



post๋ฅผ ์‚ญ์ œํ•˜๋ฉด
ํ•ด๋‹น post์˜ ์ž์‹์ธ comment๋“ค์ด ๋ชจ๋‘ ์‚ญ์ œ๋˜๊ณ 
ํ•ด๋‹น post๊ฐ€ ์‚ญ์ œ๋จ


Post

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Builder
@Entity
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Post extends BaseTimeEntity {


  ...

  @OneToMany(fetch = LAZY, //  CascadeType๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ์ถ”๊ฐ€
          mappedBy = "post",
          cascade =  {CascadeType.PERSIST, CascadeType.REMOVE}) // ๋ถ€๋ชจ ์—”ํ‹ฐํ‹ฐ๋ฅผ ์‚ญ์ œํ•˜๋ฉด ์ž์‹ ์—”ํ‹ฐํ‹ฐ ์‚ญ์ œ
  private List<Comment> comment = new ArrayList<>();

  ...
}


Comment

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Entity
@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Comment extends BaseTimeEntity {

  ...

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "post_id", nullable = false)
  private Post post; // mappedBy์— ๊ฐ™์€ ์ด๋ฆ„์œผ๋กœ ๋„ฃ์–ด์ฃผ์–ด์•ผํ•จ

  ...
  
}




(์ฐธ๊ณ )

This post is licensed under CC BY 4.0 by the author.

๐Ÿ” isPresent()๋ฅผ orElseThrow()๋กœ ๋ฐ”๊พธ๊ธฐ

๐Ÿ” ๊ฒŒ์‹œ๋ฌผ ๋‹จ์ผ ์กฐํšŒ stream ์‚ฌ์šฉํ•ด ๊ตฌํ˜„