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();