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
}
@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 ์ค๋ช
.
-
- @ManyToOne์ ์ฌ์ฉํ์ฌ ์ฌ๋ฌ ๊ฐ์ ๋๊ธ(Comment)์ด ํ๋์ ๊ฒ์๊ธ(Article)์ ์ฐธ์กฐํ๋๋ก ์ค์ ํฉ๋๋ค.
-
- @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();