[Member]
@Entity
public class Member {
@Id @GeneratedValue
private Long id;
@Column(name = "USERNAME")
private String name;
/*@Column(name = "TEAM_ID")
private Long teamId;*/
@ManyToOne
@JoinColumn(name = "TEAM_ID)
private Team team;
// getter, setter...
}
[Team]
@Entity
public class Team {
@Id @GeneratedValue
private Long id;
private String name;
// getter, setter...
}
[JpaMain]
public class JpaMain {
public static void main(String[] args) {
... 생략
// 팀저장
Team team = new Team();
team.setName("teamA");
em.persist(team);
// 회원 저장
Member member = new Member();
member.setUsername("member1");
member.setTeamId(team.getId());
em.persist(member);
// 조회
Member findMember = em.find(Member.class, member.getId());
// 참조를 사용해서 연관관계 조회
Team findTeam = findMember.getTeam();
// 새로운 팀B
Team teamB = new Team();
teamB.setName("teamB");
em.persist(teamB);
// 회원1에 새로운 팀B 설정
member.setTeam(teamB);
... 생략
}
}