Home > Backend Development > ๐Ÿ“š[Backend Development] @ManyToOne์ด๋ž€ ๋ฌด์—‡์ผ๊นŒ์š”?

๐Ÿ“š[Backend Development] @ManyToOne์ด๋ž€ ๋ฌด์—‡์ผ๊นŒ์š”?
Backend Ddevelopment

โ€œ๐Ÿ“š[Backend Development] @ManyToOne์ด๋ž€ ๋ฌด์—‡์ผ๊นŒ์š”?โ€

๐ŸŽ Intro.

  • @ManyToOne์€ ๋‹ค๋Œ€์ผ(N:1) ๊ด€๊ณ„๋ฅผ ๋งคํ•‘ํ•  ๋•Œ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.
  • ์ฆ‰, ์—ฌ๋Ÿฌ ๊ฐœ(Many)์˜ ์—”ํ‹ฐํ‹ฐ๊ฐ€ ํ•˜๋‚˜(One)์˜ ์—”ํ‹ฐํ‹ฐ๋ฅผ ์ฐธ์กฐํ•˜๋Š” ๊ตฌ์กฐ์ž…๋‹ˆ๋‹ค.

โœ…1๏ธโƒฃ @ManyToOne ์˜ˆ์ œ.

  • ๊ฒŒ์‹œ๊ธ€(Article)๊ณผ ๋Œ“๊ธ€(Comment) ๊ด€๊ณ„๋ฅผ ์˜ˆ๋กœ ๋“ค์–ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.
  • ํ•˜๋‚˜์˜ ๊ฒŒ์‹œ๊ธ€(Article)์— ์—ฌ๋Ÿฌ ๊ฐœ์˜ ๋Œ“๊ธ€(Comment)์ด ๋‹ฌ๋ฆด ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

1๏ธโƒฃ Article ์—”ํ‹ฐํ‹ฐ (๊ฒŒ์‹œ๊ธ€)

@Entity
public class Article {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    private String title;
    private String content;
    
    // Getter, Setter
}

2๏ธโƒฃ Comment ์—”ํ‹ฐํ‹ฐ (๋Œ“๊ธ€)

@Entity
public class Comment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    private String content;
    
    @ManyToOne
    @JoinColumn(name = "article_id") // ์™ธ๋ž˜ ํ‚ค ์ปฌ๋Ÿผ๋ช… ์„ค์ •
    private Article article;
    
    // Getter, Setter
}

โœ…2๏ธโƒฃ @ManyToOne ์„ค๋ช….

    1. @ManyToOne์„ ์‚ฌ์šฉํ•˜์—ฌ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ๋Œ“๊ธ€(Comment)์ด ํ•˜๋‚˜์˜ ๊ฒŒ์‹œ๊ธ€(Article)์„ ์ฐธ์กฐํ•˜๋„๋ก ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค.
    1. @JoinColumn(name = โ€œarticle_idโ€)๋ฅผ ํ†ตํ•ด comment ํ…Œ์ด๋ธ”์— article_id ์™ธ๋ž˜ ํ‚ค(FK)๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.

โœ…3๏ธโƒฃ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ํ…Œ์ด๋ธ” ๊ตฌ์กฐ.

  • ์œ„ ์ฝ”๋“œ๋ฅผ ์‹คํ–‰ํ•˜๋ฉด ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์€ ํ…Œ์ด๋ธ”์ด ์ƒ์„ฑ๋ฉ๋‹ˆ๋‹ค.

๐Ÿ“Œ article ํ…Œ์ด๋ธ”

id title content
1 โ€œHello JPAโ€ โ€œJPA ๋ฐฐ์šฐ๊ธฐโ€
2 โ€œSpring Bootโ€ โ€œSpring ๊ณต๋ถ€โ€

๐Ÿ“Œ comment ํ…Œ์ด๋ธ” (article_id FK ํฌํ•จ)

id content article_id(FK)
1 โ€œ์ข‹์€ ๊ธ€์ด๋„ค์š”!โ€ 1
2 โ€œ์œ ์ตํ•œ ์ •๋ณด ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.โ€ 1
3 โ€œSpring ์ตœ๊ณ !โ€ 2
  • ๐Ÿ“Œ article_id ์ปฌ๋Ÿผ์ด ๊ฒŒ์‹œ๊ธ€(Article)์„ ์ฐธ์กฐํ•˜๋Š” ์™ธ๋ž˜ ํ‚ค(FK)์ž…๋‹ˆ๋‹ค.
    • ์ฆ‰, comment ํ…Œ์ด๋ธ”์˜ ์—ฌ๋Ÿฌ ํ–‰์ด article_id๋ฅผ ํ†ตํ•ด ๊ฐ™์€ article์„ ๊ฐ€๋ฆฌํ‚ฌ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

โœ…4๏ธโƒฃ ๋ฐ์ดํ„ฐ ์กฐํšŒ

โœ… ํŠน์ • ๊ฒŒ์‹œ๊ธ€์— ์†ํ•œ ๋Œ“๊ธ€ ๊ฐ€์ ธ์˜ค๊ธฐ.

  • ๊ฒŒ์‹œ๊ธ€ ID(articleId)๊ฐ€ 1๋ฒˆ์ธ ๋Œ“๊ธ€์„ ๊ฐ€์ ธ์˜ค๋ ค๋ฉด:
List<Comment> comments = entityManager.createQuery(
        "SELECT c FROM c WHERE c.article.id = :articleId", Comment.class)
    .setParameter("articleId", 1L)
    .getResultList();