QueryDSL - 조인

목차

기본 조인

첫 번째 파라미터에 조인 대상을 지정하고, 두번째 파라미터에 별칭으로 사용할 Q 타입을 지정하면 된다.

@Test
public void join(){
List<Member> result = queryFactory.selectFrom(member)
.join(member.team, team)
.where(team.name.eq("teamA"))
.fetch();

assertThat(result)
.extracting("username")
.containsExactly("member1", "member2");
}
/* select
member1
from
Member member1
inner join
member1.team as team
where
team.name = ?1 */ select
member0_.member_id as member_i1_1_,
member0_.age as age2_1_,
member0_.team_id as team_id4_1_,
member0_.username as username3_1_
from
member member0_
inner join
team team1_
on member0_.team_id=team1_.team_id
where
team1_.name=?

Seta Join

  • From 절에 여러 엔티티를 선택해서 세타 조인이 가능하다.
  • 외부 조인 불가능
    • 조인 on 을 사용하면 외부 조인 가능
@Test
public void setaJoin(){
em.persist(new Member("teamA"));
em.persist(new Member("teamB"));

List<Member> result = queryFactory.select(member)
.from(member, team)
.where(member.username.eq(team.name))
.fetch();

assertThat(result)
.extracting("username")
.containsExactly("teamA", "teamB");
}
/* select
member1
from
Member member1,
Team team
where
member1.username = team.name */ select
member0_.member_id as member_i1_1_,
member0_.age as age2_1_,
member0_.team_id as team_id4_1_,
member0_.username as username3_1_
from
member member0_ cross
join
team team1_
where
member0_.username=team1_.name

ON절을 이용한 JOIN

  • on 절을 활용한 조인
    • 조인 대상 필터링
    • 연관관계 없는 엔티티 외부 조인
@Test
public void join_on_filtering() {
List<Tuple> result = queryFactory
.select(member, team)
.from(member)
.leftJoin(member.team, team).on(team.name.eq("teamA"))
.fetch();

for (Tuple tuple : result) {
System.out.println("tuple = " + tuple);
}
}
/* select
member1,
team
from
Member member1
left join
member1.team as team with team.name = ?1 */ select
member0_.member_id as member_i1_1_0_,
team1_.team_id as team_id1_2_1_,
member0_.age as age2_1_0_,
member0_.team_id as team_id4_1_0_,
member0_.username as username3_1_0_,
team1_.name as name2_2_1_
from
member member0_
left outer join
team team1_
on member0_.team_id=team1_.team_id
and (
team1_.name=?
)

연관관계가 없는 엔티티 외부 조인

@Test
public void join_on_no_relation(){
em.persist(new Member("teamA"));
em.persist(new Member("teamB"));
em.persist(new Member("teamB"));

List<Tuple> fetch = queryFactory
.select(member, team)
.from(member)
.leftJoin(team).on(member.username.eq(team.name))
.fetch();

for (Tuple tuple : fetch) {
System.out.println("tuple = " + tuple);
}
}
/* select
member1,
team
from
Member member1
left join
Team team with member1.username = team.name */ select
member0_.member_id as member_i1_1_0_,
team1_.team_id as team_id1_2_1_,
member0_.age as age2_1_0_,
member0_.team_id as team_id4_1_0_,
member0_.username as username3_1_0_,
team1_.name as name2_2_1_
from
member member0_
left outer join
team team1_
on (
member0_.username=team1_.name
)
Share