1) 즉시로딩
2) 지연로딩
@ManyToOne 디폴트값은 FetchType.EAGER(한꺼번에 쿼리)
@ManyToOne(fetch = FetchType.LAZY) //지연로딩 사용해서 프록시로 조회
@JoinColumn(name = "TEAM_ID")
private TeamMapping team;
TeamMapping team = new TeamMapping();
team.setName("teamA");
em.persist(team);
MemberMapping member1 = new MemberMapping();
member1.setUsername("hello");
member1.setTeam(team);
em.persist(member1);
em.flush();
em.clear();
MemberMapping m = em.find(MemberMapping.class, member1.getId()); //영속성 컨텍스트에 올라감
System.out.println("m = " + m.getTeam().getClass()); //proxy
System.out.println("==============");
m.getTeam().getName(); //프록시 초기화(이 시점에 team 조회 쿼리)
System.out.println("==============");
tx.commit();
m = class hellojpa.mapping.TeamMapping$HibernateProxy$Js9npXxJ
==============
Hibernate:
select
teammappin0_.TEAM_ID as team_id1_12_0_,
teammappin0_.createdAt as createda2_12_0_,
teammappin0_.createdBy as createdb3_12_0_,
teammappin0_.updatedAt as updateda4_12_0_,
teammappin0_.updatedBy as updatedb5_12_0_,
teammappin0_.name as name6_12_0_
from
TeamMapping teammappin0_
where
teammappin0_.TEAM_ID=?
==============
m again = class hellojpa.mapping.TeamMapping$HibernateProxy$Js9npXxJ
9월 11, 2022 9:54:25 오후 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PoolState stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:h2:tcp://localhost/~/test]
Process finished with exit code 0
📌실무에서 주의할 점
List <Member> members = em.createQuery("select m from Member m", Member.class).getResultList();
- @ManyToOne, @OneToOne은 기본이 즉시로딩 => 직접 LAZY로 설정 필요
- @OneToMany, @ManyToMany는 기본이 지연로딩