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