@Entity
public class MemberMapping {
@Id
@GeneratedValue
@Column(name = "MEMBER_ID")
private Long id;
@Column(name = "USERNAME")
private String username;
@Column(name = "TEAM_ID")
private Long teamId;
//...getter, setter
}
@Entity
public class TeamMapping {
@Id
@GeneratedValue
@Column(name = "TEAM_ID")
private Long id;
private String name;
//...getter, setter
}
//팀 저장
TeamMapping team = new TeamMapping();
team.setName("teamA");
em.persist(team);
//멤버 저장
MemberMapping member = new MemberMapping();
member.setUsername("member1");
member.setTeamId(team.getId()); //외래키 식별자를 직접 저장
em.persist(member);
//조회
MemberMapping findMember = em.find(MemberMapping.class, member.getId());
Long findTeamId = findMember.getTeamId();
TeamMapping findTeam = em.find(TeamMapping.class, findTeamId);
@Entity
public class MemberMapping {
@Id
@GeneratedValue
@Column(name = "MEMBER_ID")
private Long id;
@Column(name = "USERNAME")
private String username;
private TeamMapping team; //팀의 참조 보관
//...getter, setter
}
@Entity
public class TeamMapping {
@Id
@GeneratedValue
@Column(name = "TEAM_ID")
private Long id;
private String name;
//...getter, setter
}
//팀 저장
TeamMapping team = new TeamMapping();
team.setName("teamA");
//멤버 저장
MemberMapping member = new MemberMapping();
member.setUsername("member1");
member.setTeam(team);
//조회
TeamMapping findTeam = member.getTeam();
@Entity
public class MemberMapping {
@Id
@GeneratedValue
@Column(name = "MEMBER_ID")
private Long id;
@Column(name = "USERNAME")
private String username;
@ManyToOne
@JoinColumn(name = "TEAM_ID")
private TeamMapping team;
//...getter, setter
}
@Entity
public class TeamMapping {
@Id
@GeneratedValue
@Column(name = "TEAM_ID")
private Long id;
private String name;
//...getter, setter
}
1) 등록
//팀 저장
TeamMapping team = new TeamMapping();
team.setName("teamA");
em.persist(team);
//멤버1 저장
MemberMapping member1= new MemberMapping();
member.setUsername("member1");
member.setTeam(team); //연관관계 설정: member1 -> team
em.persist(member1);
//멤버2 저장
MemberMapping member2 = new MemberMapping();
member.setUsername("member2");
member.setTeam(team); //연관관계 설정: member2 -> team
em.persist(member2);
🚫 JPA에서 엔티티 저장시 연관된 모든 엔티티는 영속 상태!!!
2) 조회
MemberMapping findMember = em.find(MemberMapping.class, member.getId());
TeamMapping findTeam = findMember.getTeam();
3) 수정
MemberMapping findMember = em.find(MemberMapping.class, member.getId());
TeamMapping newTeam = em.find(TeamMapping.class, 100L);
findMember.setTeam(newTeam);
4) 연관관계 제거
MemberMapping findMember = em.find(MemberMapping.class, member.getId());
findMember.setTeam(null);
5) 연관된 엔티티 삭제
MemberMapping findMember = em.find(MemberMapping.class, member.getId());
findMember.setTeam(null); //연관관계 제거
em.remove(team); //팀 삭제