๋ฐ์ํ
์๋ฐ ORM ํ์ค JPA ํ๋ก๊ทธ๋๋ฐ - ๊ธฐ๋ณธํธ์ ๊ณต๋ถํ๋ฉฐ ์ ๋ฆฌํ ๋ด์ฉ์ ๋๋ค.
โ ๊ฐ์ฒด ์งํฅ ๋ชจ๋ธ๋ง ( ๊ฐ์ฒด ์ฐ๊ด๊ด๊ณ ์ฌ์ฉ )
@Entity
public class Member {
@Id @GenerateValue
private Long id;
@ManyToOne // Member์์ ์ผ๋ก ๋ค๋์ผ์ด๋ฏ๋ก, ManyToOne!
@JoinColumn(name = "TEAM_ID")
private Team team;
@Column(name = "USERNAME")
private String name;
}
@ManyToOne @JoinColumn(name = "TEAM_ID") ์ผ๋ก ์ฐ๊ด๊ด๊ณ๋ฅผ ๋งคํ์์ผ์ค๋ค.
@Entity
public class Team {
@Id @GenerateValue
private Long id;
private String name;
}
โ ๊ฐ์ฒด ์งํฅ ๋ชจ๋ธ๋ง ( ORM ๋งคํ )
์ฐ๊ด๊ด๊ณ ์ ์ฅ
Team team = new Team();
...
em.persist(team);
Member member = new Member();
...
member.setTeam(team); // ๋จ๋ฐฉํฅ ์ฐ๊ด๊ด๊ณ ์ค์ , ์ฐธ์กฐ ์ ์ฅ
em.persist(member);
์ฐธ์กฐ๋ก ์ฐ๊ด๊ด๊ณ ์กฐํ
//์กฐํ
Member findMember = em.find(Member.class , member.getId());
//์ฐธ์กฐ๋ฅผ ์ฌ์ฉํด์ ์ฐ๊ด๊ด๊ณ ์กฐํ
Team FindTeam = findMember.getTeam();
์ฐ๊ด๊ด๊ณ ์์
// ์๋ก์ด Team
Team teamB = new Team();
teamB.setName("TeamB");
em.persist(teamB);
// member์ ์๋ก์ด Team์ผ๋ก ์์
member.setTeam(teamB);
๋ค์์ผ๋ก๋, "์๋ฐฉํฅ ์ฐ๊ด๊ด๊ณ์ ์ฃผ์ธ"์ ๋ํด์ ๊ณต๋ถํด๋ณด์.
๋ฐ์ํ