작성
·
184
0
안녕하세요 영한님 서포터즈님들
다름이 아니라 제가 이번에 jpa 2편 듣다가 페치조인에 대해 다시 공부하러 왔습니다.
강의를 2번 듣고도 너무 헷갈렸습니다.
혹시나 저처럼 페치 조인에 허덕이는 분들을 위해 코드 올려봅니다
단지 영한님 코드를 종합해서 한 것이지만,
머리가 아닌 손으로 이 때는 쿼리가 나가는지, 이 때는 쿼리가 왜 안나가는지 하나하나 혼자 납득시키며 공부하시면
어느새 페치 조인이 이해되실 겁니다
제가 몇 일간 이해하는데 힘들어서 조금이나마 도움이 됐으면 좋겠습니다.
Team team1 = new Team();
team1.setName("Team1");
em.persist(team1);
Team team2 = new Team();
team2.setName("Team2");
em.persist(team2);
Member member1 = new Member();
member1.setUsername("회원1");
member1.changeTeam(team1);
em.persist(member1);
Member member2 = new Member();
member2.setUsername("회원2");
member2.changeTeam(team1);
em.persist(member2);
Member member3 = new Member();
member3.setUsername("회원3");
member3.changeTeam(team2);
em.persist(member3);
em.flush();
em.clear();
//1. 단일 값 일반 join
String query1 = "select m from Member m join m.team";
//2. 단일 값 fetch join
String query2 = "select m from Member m join fetch m.team";
//3. 컬렉션 값 일반 join
String query3 = "select t from Team t join t.members";
//4. 컬렉션 값 fetch join
String query4 = "select t from Team t join fetch t.members";
System.out.println("============1. 엔티티 조인===============");
List<Member> resultList = em.createQuery(query1, Member.class)
.getResultList();
for (Member member : resultList) {
System.out.println("member = " + member.getUsername() + "," + "팀: " + member.getTeam().getName());
}
em.clear();
System.out.println("============2. 엔티티 페치 조인================");
List<Member> resultList1 = em.createQuery(query2, Member.class)
.getResultList();
for (Member member : resultList1) {
System.out.println("member = " + member.getUsername() + "," + "팀: " + member.getTeam().getName());
}
em.clear();
System.out.println("============3. 컬렉션 조인================");
List<Team> resultList2 = em.createQuery(query3, Team.class)
.getResultList();
for (Team team : resultList2) {
System.out.println("team: " + team.getName());
for (Member member : team.getMembers()) {
System.out.println("-> member = " + member.getUsername() + " ");
}
}
em.clear();
System.out.println("============4. 컬렉션 페치 조인================");
List<Team> resultList3 = em.createQuery(query4, Team.class)
.getResultList();
for (Team team : resultList3) {
System.out.println("team: " + team.getName());
for (Member member : team.getMembers()) {
System.out.println("-> member = " + member.getUsername() + " ");
}
System.out.println();
}
tx.commit();