songining
article thumbnail
Published 2022. 1. 16. 17:25
ํ”„๋ก์‹œ BACKEND/Spring

- ์‹ค์ œ ์—”ํ‹ฐํ‹ฐ๋ฅผ ์ƒ์†๋ฐ›์•„ ๋งŒ๋“ค์–ด์ง(๋”ฐ๋ผ์„œ ๊ฒ‰๋ชจ์–‘์ด ๊ฐ™๋‹ค)

- ํ”„๋ก์‹œ ๊ฐ์ฒด๋Š” ์‹ค์ œ ๊ฐ์ฒด์˜ ์ฐธ์กฐ(target)์„ ๋ณด๊ด€ 

- ํ”„๋ก์‹œ ๊ฐ์ฒด๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด ํ”„๋ก์‹œ ๊ฐ์ฒด๋Š” ์‹ค์ œ ๊ฐ์ฒด์˜ ๋ฉ”์†Œ๋“œ ํ˜ธ์ถœ 

 

** ํ”„๋ก์‹œ ๊ฐ์ฒด๋Š” ์›๋ณธ ์—”ํ‹ฐํ‹ฐ๋ฅผ ์ƒ์†๋ฐ›์Œ . ํ”„๋ก์‹œ ๊ฐ์ฒด๋ฅผ ์ดˆ๊ธฐํ™”ํ•  ๋•Œ, ํ”„๋ก์‹œ ๊ฐ์ฒด๊ฐ€ ์‹ค์ œ ์—”ํ‹ฐํ‹ฐ๋กœ ๋ฐ”๋€Œ๋Š” ๊ฒƒ์€ ์•„๋‹˜.

์ดˆ๊ธฐํ™”๋˜๋ฉด ํ”„๋ก์‹œ ๊ฐ์ฒด๋ฅผ ํ†ตํ•ด์„œ ์‹ค์ œ ์—”ํ‹ฐํ‹ฐ์— ์ ‘๊ทผ ๊ฐ€๋Šฅ 

์˜์†์„ฑ ์ปจํ…์ŠคํŠธ์— ์ฐพ๋Š” ์—”ํ‹ฐํ‹ฐ๊ฐ€ ์ด๋ฏธ ์žˆ์œผ๋ฉด em.getReference() ํ˜ธ์ถœํ•ด๋„ ์‹ค์ œ ์—”ํ‹ฐํ‹ฐ ๋ฐ˜ํ™˜

Member findMember = em.getReference(Member.class, member); //๋นˆ ๊ป๋ฐ๊ธฐ(ํ”„๋ก์‹œ)
//getUsername()์‹œ์— ์‹ค์ œ ์ฟผ๋ฆฌ ์‹คํ–‰ -> ํ”„๋ก์‹œ ์ดˆ๊ธฐํ™”
System.out.println("findMember.username=" + findMember.getUsername());
System.out.println("findMember.username=" + findMember.getUsername());

 

์ง€์—ฐ๋กœ๋”ฉ (fetch = FetchType.LAZY)

-> ์ง€์—ฐ๋กœ๋”ฉ์œผ๋กœ ์„ค์ •์‹œ em.find()ํ•œ ๊ฒฝ์šฐ ์—ฐ๊ด€๋œ ๊ฐ์ฒด๋ฅผ ํ”„๋ก์‹œ๋กœ ๊ฐ€์ ธ์˜จ๋‹ค. 

-> member ์ฟผ๋ฆฌ ๋”ฐ๋กœ select~, team ํ•„์š”ํ•œ ์‹œ์ ์— team ์ฟผ๋ฆฌ ๋”ฐ๋กœ select ~

์‹ค์ œ team์„ ์‚ฌ์šฉํ•˜๋Š” ์‹œ์ ์— ์ดˆ๊ธฐํ™” ๋ฐ DB ์ฟผ๋ฆฌ์‹คํ–‰ (Ex) team.getName();)

 

 

์ฆ‰์‹œ๋กœ๋”ฉ(fetch=FetchType.EAGER)

-> Member์™€ Team์„ ๊ณ„์† ๊ฐ™์ด ์‚ฌ์šฉํ•œ๋‹ค๋ฉด ์ด๋ ‡๊ฒŒ ๋ฐ”๋กœ ๋กœ๋”ฉํ•˜์—ฌ ์กฐ์ธํ•ด์„œ ํ•จ๊ป˜ ๊ฐ€์ ธ์˜ค๋Š” ๊ฒƒ์ด ์œ ๋ฆฌ

-> ํ•œ๋ฒˆ์— joinํ•ด์„œ ๊ฐ€์ ธ์˜ค๊ธฐ ๋•Œ๋ฌธ์— member์— ๋งž๋Š” Team ์ฟผ๋ฆฌ๊ฐ€ ํ•จ๊ป˜ ์ž”๋œฉ ๋‚˜๊ฐ„๋‹ค.

 

 

๊ฐ€๊ธ‰์  ์ง€์—ฐ๋กœ๋”ฉ๋งŒ ์‚ฌ์šฉ!!! why? ์—ฐ๊ด€๋œ ์—”ํ‹ฐํ‹ฐ๋ฅผ ์ „๋ถ€ ๋Œ์–ด์˜ค๋ฏ€๋กœ ์˜ˆ์ƒ์น˜ ๋ชปํ•œ SQL ๋ฐœ์ƒ

๋”ฐ๋ผ์„œ ์ผ๋‹จ ์ „๋ถ€ ์ง€์—ฐ ๋กœ๋”ฉ ์ ์šฉํ•œ ํ›„, Member์™€ Team ๊ฐ™์ด ๊ฐ€์ ธ์™€์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ Fetch JOIN ์‚ฌ์šฉ