Team.java
@Entity
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Getter
@Setter
@ToString
public class Team {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "team")
@Builder.Default
private List<Member> members = new ArrayList<>();
public void addMember(Member member) {
member.setTeam(this);
members.add(member);
}
}
Member.java
@Entity
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Getter
@Setter
@ToString
public class Member {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int age;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "team_id")
private Team team;
}
@Query("SELECT distinct t FROM Team t JOIN t.members")
public List<Team> findAllWithMembersUsingJoin();
Hibernate:
select
distinct team0_.id as id1_1_,
team0_.name as name2_1_
from team team0_
inner join
member members1_
on team0_.id=members1_.team_id
- 일반 Join으로 Team Entity 초기화 완료
- 하지만 일반 Join은 연관 Entity까지 초기화하지 않기 때문에 Member는 초기화되지 않음
- toString()으로 아직 초기화되지 않은 members에 접근하면서 LazyInitializationException 발생(실제로 Team에 @ToString(exclude="members")를 설정하게 되면 members에 접근하지 않게 되고 LazyInitializationException 또한 발생하지 않게 됨)
@Query("SELECT distinct t FROM Team t JOIN FETCH t.members")
public List<Team> findAllWithMembersUsingFetchJoin();
Hibernate:
select
distinct team0_.id as id1_1_,
members1_.id as id1_0_1_,
team0_.name as name2_1_,
members1_.age as age2_0_1,
members1_.name as name3_0_1_,
members1_.team_id as team_id4_0_1_,
members1_.team_id as team_id4_0_1_,
members1_.id as id1_0_1_
from team team0_
inner join
member members1_
on team0_.id=members1_.team_id
https://frogand.tistory.com/156
https://cobbybb.tistory.com/18