본문 바로가기
Java/JPA

[JPA_Basic] 객체 지향 모델링

by HJ0216 2023. 8. 8.

이 글은 김영한의 [자바 ORM 표준 JPA 프로그래밍 - 기본편] 수강하며 정리한 글입니다.

 

👉 기본 환경

- Language: Java

- DB: H2 Database

- IDE: IntelliJ

 

 

1. 객체를 테이블에 맞춰 모델링

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package jpa_basic;
 
import javax.persistence.*;
import java.util.Date;
 
@Entity
public class Member {
 
    @Id @GeneratedValue
    @Column(name = "MEMBER_ID")
    private Long id;
 
    @Column(name = "USERNAME")
    private String name;
 
    @Column(name = "TEAM_ID")
    private Long teamId;
 
    public Long getId() {
        return id;
    }
 
    public void setId(Long id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public Long getTeamId() {
        return teamId;
    }
 
    public void setTeamId(Long teamId) {
        this.teamId = teamId;
    }
 
 
}
 
 
 

테이블에서 외래키 역할을 하는 teamId가 필드로 선언

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.List;
 
public class Main {
 
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
 
        EntityManager em = emf.createEntityManager();
 
        // JPA의 모든 데이터 변경은 transaction 안에서 실행
        EntityTransaction tx = em.getTransaction();
        tx.begin();
 
        try {
 
            // 객체를 테이블에 맞춰 모델링
 
            Team team = new Team();
            team.setName("TeamA");
            em.persist(team);
 
            Member member = new Member();
            member.setName("Member1");
            member.setTeamId(team.getId());
            em.persist(member);
 
            Member findMember = em.find(Member.class, member.getId());
 
            Long findTeamId = findMember.getTeamId();
            Team findItem = em.find(Team.class, findTeamId);
 
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            em.close();
        }
 
 
        emf.close();
 
    }
 
}
 
 
 

* DB에 맞춰진 설계 방식

    - Member와 Team 사이의 연관관계를 맺는 대신에 teamId를 사용하여 직접적인 관계를 표현

    - OOP에서는 객체 간의 관계를 통해 참조하는 것이 일반적

    - ID 값보다는 실제 객체의 참조를 사용하여 관계를 표현하는 것이 객체 지향적인 방식

    - 객체 간의 연관관계를 활용하여 코드의 가독성과 유지보수성을 높일 수 있음

 

 

2. 객체 지향 모델링

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package jpa_basic;
 
import javax.persistence.*;
import java.util.Date;
 
@Entity
public class Member {
 
    @Id @GeneratedValue
    @Column(name = "MEMBER_ID")
    private Long id;
 
    @Column(name = "USERNAME")
    private String name;
 
    @ManyToOne // Member : Team = Many : One
    @JoinColumn(name = "TEAM_ID"// JoinColumn = FK
    private Team team;
 
    public Long getId() {
        return id;
    }
 
    public void setId(Long id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public Team getTeam() {
        return team;
    }
 
    public void setTeam(Team team) {
        this.team = team;
    }
 
}
 
 
 

Entity Team을 필드로 선언하여 연관관계 매핑

Entity 간의 관계 설정(@ManyToOne, Member : Team = 다 : 1)

관계 설정 시, FK 설정(@JoinColumn)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package jpa_basic;
 
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.List;
 
public class Main {
    public static void main(String[] args) {
 
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
 
        EntityManager em = emf.createEntityManager();
 
        EntityTransaction tx = em.getTransaction();
        tx.begin();
 
        try {
 
            // 객체 지향 모델링
            Team team = new Team();
            team.setName("TeamA");
            em.persist(team);
 
            Member member = new Member();
            member.setName("Member1");
            member.setTeam(team);
            em.persist(member);
 
            Member findMember = em.find(Member.class, member.getId());
 
            Team findTeam = findMember.getTeam();
 
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            em.close();
        }
 
 
        emf.close();
    }
 
}
 
 
 

ID 값을 사용하는 대신 Team 객체 사용