김영한님이 지음, [자바 ORM 표준 JPA 프로그래밍] 책을 읽고 정리한 필기입니다.📢
연관관계 사용
저장
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void testSave(EntityManager em){
//팀1 저장
Team team1 = new Team("team1", "팀1");
em.persist(team1);
//회원1 저장
Member member1 = new Member("member1", "회원1");
member1.setTeam(team1); //연관관계 설정 member1 -> team1
//회원2 저장
Member member2 = new Member("member2", "회원2");
member2.setTeam(team1); //연관관계 설정 member2 -> team1
em.persist(member2);
}
⚠️ JPA에서 엔티티를 저장할 때 연관된 모든 엔티티는 영속 상태여야 한다.
출력된 SQL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Hibernate:
/* insert org.example.Team
*/ insert
into
Team
(name, TEAM_ID)
values
(?, ?)
Hibernate:
/* insert org.example.Member
*/ insert
into
Member
(TEAM_ID, NAME, MEMBER_ID)
values
(?, ?, ?)
Hibernate:
/* insert org.example.Member
*/ insert
into
Member
(TEAM_ID, NAME, MEMBER_ID)
values
(?, ?, ?)
결과
결과
조회
연관관계가 있는 엔티티를 조회하는 방법 2가지
- 객체 그래프 탐색(객체 연관관계를 사용한 조회)
- 객체지향 쿼리 사용(JPQL)
객체 그래프 탐색
1
2
3
4
5
Member member = em.find(Member.class, "member1");
Team team = member.getTeam(); //객체 그래프 탐색
System.out.println("팀 이름 = " + team.getName());
//출력 결과 : 팀 이름=팀1
객체지향 쿼리 사용(JPQL)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private static void queryLogicJoin(EntityManager em){
String jpql = "select m from Member m join m.team t where t.name=:teamName";
List<Member> resultList = em.createQuery(jpql, Member.class)
.setParameter("teamName", "팀1")
.getResultList();
for(Member member : resultList){
System.out.println("[query] member.username=" + member.getUsername());
}
}
//출력 결과
//[query] member.username=회원1
//[query] member.username=회원2
출력된 SQL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Hibernate:
/* select
m
from
Member m
join
m.team t
where
t.name=:teamName */ select
member0_.MEMBER_ID as member_i1_0_,
member0_.TEAM_ID as team_id8_0_,
member0_.NAME as name7_0_
from
Member member0_
inner join
Team team1_
on member0_.TEAM_ID=team1_.TEAM_ID
where
team1_.name=?
수정
1
2
3
4
5
6
7
8
9
private static void updateRelation(EntityManager em){
//새로운 팀2
Team team2 = new Team("team2", "팀2");
em.persist(team2);
//회원1에 새로운 팀2 설정
Member member = em.find(Member.class, "member1");
member.setTeam(team2);
}
출력된 SQL
1
2
3
4
5
6
7
8
9
Hibernate:
/* update
org.example.Member */ update
Member
set
TEAM_ID=?,
NAME=?
where
MEMBER_ID=?
연관관계 제거
1
2
3
4
private static void deleteRelation(EntityManager em){
Member member1 = em.find(Member.class, "member1");
member1.setTeam(null);
}
출력된 SQL
1
2
3
4
5
6
7
8
9
Hibernate:
/* update
org.example.Member */ update
Member
set
TEAM_ID=?,
NAME=?
where
MEMBER_ID=?
연관된 엔티티 삭제
연관 에티티를 삭제하려면 기존에 있던 연관관계를 먼저 제거하고 삭제해야 함, 그렇지 않으면 데이터베이스에서 제약조건 위반 에러가 발생함
1
2
3
member1.setTeam(null); //회원1 연관관계 제거
member2.setTeam(null); //회원2 연관관계 제거
em.remove(team);
댓글남기기