이 글은 김영한의 [자바 ORM 표준 JPA 프로그래밍 - 기본편]을 수강하며 정리한 글입니다.
👉 기본 환경
- Language: Java
- DB: H2 Database
- IDE: IntelliJ
Fetch Join
- Fetch Join 대상에는 alias를 줄 수 X
- Hibernate는 가능하지만, 가급적 사용 X
- 2 이상의 컬렉션은 Fetch Join X
- Collection Fetch Join 시, 페이징 API 사용 X
- 일대일, 다대일 같은 단일 값 연관 필드들은 페이징 가능
- 🚨 Hibernate는 경고 Log를 남기고 페이징 처리를 하지만, 사용하지 않는 것을 권장
Collection과 Fetch Join 대안
1. 일대다 관계 ▶ 다대일 관계로 변경해서 fetch join
일대다 관계
⌨️ 코드
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
50
51
52
53
54
55
56
57
58
59
60
61
|
public class Main {
public static void main(String[] args) {
//
try {
Team teamA = new Team();
teamA.setName("TeamA");
em.persist(teamA);
Team teamB = new Team();
teamB.setName("TeamB");
em.persist(teamB);
Member memberA = new Member();
memberA.setName("MemberA");
memberA.setTeam(teamA);
em.persist(memberA);
Member memberB = new Member();
memberB.setName("memberB");
memberB.setTeam(teamA);
em.persist(memberB);
Member memberC = new Member();
memberC.setName("memberC");
memberC.setTeam(teamB);
em.persist(memberC);
em.flush();
em.clear();
String query = "select t from Team t join fetch t.members ";
List<Team> teams = em.createQuery(query, Team.class)
.setFirstResult(0)
.setMaxResults(1)
.getResultList();
for (Team t : teams){
System.out.println("Team: " + t.getName());
for(Member m: t.getMembers()){
System.out.println(" -> Member: " + m);
}
}
tx.commit(); // transaction 종료 후 commit
} catch (Exception e) {
tx.rollback(); // 문제가 생길 경우, rollback 진행
e.printStackTrace();
} finally {
em.close(); // tx에 문제가 생기더라도 em 반드시 종료
}
emf.close();
// 트랜잭션 단위로 관리되는 Entity Manager는 Tx가 종료되면 close가 되어야하지만, emf는 Application 종료 시, close되어야 함
}
}
|
🖨️발생한 쿼리
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
|
WARN: HHH000104: firstResult/maxResults specified with collection fetch; applying in memory!
Hibernate:
/* select
t
from
Team t
join
fetch t.members */ select
team0_.id as id1_3_0_,
members1_.id as id1_0_1_,
team0_.name as name2_3_0_,
members1_.age as age2_0_1_,
members1_.name as name3_0_1_,
members1_.TEAM_ID as team_id5_0_1_,
members1_.type as type4_0_1_,
members1_.TEAM_ID as team_id5_0_0__,
members1_.id as id1_0_0__
from
Team team0_
inner join
Member members1_
on team0_.id=members1_.TEAM_ID
Team: TeamA
-> Member: Member{id=3, name='MemberA', age=0}
-> Member: Member{id=4, name='memberB', age=0}
|
다대일 관계
⌨️ 코드
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
50
51
52
53
54
55
56
57
58
|
public class Main {
public static void main(String[] args) {
// 생략
try {
Team teamA = new Team();
teamA.setName("TeamA");
em.persist(teamA);
Team teamB = new Team();
teamB.setName("TeamB");
em.persist(teamB);
Member memberA = new Member();
memberA.setName("MemberA");
memberA.setTeam(teamA);
em.persist(memberA);
Member memberB = new Member();
memberB.setName("memberB");
memberB.setTeam(teamA);
em.persist(memberB);
Member memberC = new Member();
memberC.setName("memberC");
memberC.setTeam(teamB);
em.persist(memberC);
em.flush();
em.clear();
String query = "select m from Member m join fetch m.team t";
List<Member> members = em.createQuery(query, Member.class)
.setFirstResult(0)
.setMaxResults(1)
.getResultList();
for (Member m : members){
System.out.println("Team: " + m.getTeam().getName());
}
tx.commit(); // transaction 종료 후 commit
} catch (Exception e) {
tx.rollback(); // 문제가 생길 경우, rollback 진행
e.printStackTrace();
} finally {
em.close(); // tx에 문제가 생기더라도 em 반드시 종료
}
emf.close();
// 트랜잭션 단위로 관리되는 Entity Manager는 Tx가 종료되면 close가 되어야하지만, emf는 Application 종료 시, close되어야 함
}
}
|
🖨️발생한 쿼리
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
Hibernate:
/* select
m
from
Member m
join
fetch m.team t */ select
member0_.id as id1_0_0_,
team1_.id as id1_3_1_,
member0_.age as age2_0_0_,
member0_.name as name3_0_0_,
member0_.TEAM_ID as team_id5_0_0_,
member0_.type as type4_0_0_,
team1_.name as name2_3_1_
from
Member member0_
inner join
Team team1_
on member0_.TEAM_ID=team1_.id limit ?
Team: TeamA
|
2. Batch_size 사용
Collection field에 @BatchSize 추가
⌨️ 코드
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
50
51
52
53
54
55
56
57
58
59
60
61
|
public class Main {
public static void main(String[] args) {
// 생략
try {
Team teamA = new Team();
teamA.setName("TeamA");
em.persist(teamA);
Team teamB = new Team();
teamB.setName("TeamB");
em.persist(teamB);
Member memberA = new Member();
memberA.setName("MemberA");
memberA.setTeam(teamA);
em.persist(memberA);
Member memberB = new Member();
memberB.setName("memberB");
memberB.setTeam(teamA);
em.persist(memberB);
Member memberC = new Member();
memberC.setName("memberC");
memberC.setTeam(teamB);
em.persist(memberC);
em.flush();
em.clear();
String query = "select t from Team t";
List<Team> teams = em.createQuery(query, Team.class)
.setFirstResult(0)
.setMaxResults(2)
.getResultList();
for (Team t : teams){
System.out.println("Team: " + t.getName());
for(Member m: t.getMembers()){
System.out.println(" -> Member: " + m);
}
}
tx.commit(); // transaction 종료 후 commit
} catch (Exception e) {
tx.rollback(); // 문제가 생길 경우, rollback 진행
e.printStackTrace();
} finally {
em.close(); // tx에 문제가 생기더라도 em 반드시 종료
}
emf.close();
// 트랜잭션 단위로 관리되는 Entity Manager는 Tx가 종료되면 close가 되어야하지만, emf는 Application 종료 시, close되어야 함
}
}
|
cf. Batch size Global Setting
persistence.xml에 "<property name="hibernate.default_batch_fetch_size" value="100"/>" 추가
🖨️발생한 쿼리
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
|
Hibernate:
/* select
t
from
Team t */ select
team0_.id as id1_3_,
team0_.name as name2_3_
from
Team team0_ limit ?
Team: TeamA
Hibernate:
/* load one-to-many jpql.Team.members */ select
members0_.TEAM_ID as team_id5_0_1_,
members0_.id as id1_0_1_,
members0_.id as id1_0_0_,
members0_.age as age2_0_0_,
members0_.name as name3_0_0_,
members0_.TEAM_ID as team_id5_0_0_,
members0_.type as type4_0_0_
from
Member members0_
where
members0_.TEAM_ID in (
?, ?
)
-> Member: Member{id=3, name='MemberA', age=0}
-> Member: Member{id=4, name='memberB', age=0}
Team: TeamB
-> Member: Member{id=5, name='memberC', age=0}
|
Batch Size만큼 in query 발생
3. DTO 활용
- fetch join의 결과 → DTO 변환
- jpql 작성 시, new DTO 사용
⭐ 실무에서 글로벌 로딩 전략은 모두 지연 로딩으로 하고, 최적화가 필요한 곳에 페치 조인 적용
⭐ 여러 테이블을 조인해서 엔티티가 가진 모양이 아닌 전혀 다른 결과를 내야 한다면,
페치 조인보다는 일반 조인을 사용하고 필요한 데이터들만 조회해서 DTO로 반환하는 것이 효과적
'Java > JPA' 카테고리의 다른 글
[JPA_Basic] Bulk 연산 (0) | 2023.09.29 |
---|---|
[JPA_Basic] Fetch Join (0) | 2023.09.27 |
[JPA_Basic] 경로 표현식 (0) | 2023.09.26 |
[JPA_Basic] JPQL 타입 표현과 기타식 (1) | 2023.09.25 |
[JPA_Basic] 조인 (0) | 2023.09.23 |