[Spring Framwork] LazyInitializationException / @EntityGraph

2021. 11. 16. 20:01ใ†๊ฐœ๋… ์ •๋ฆฌ ์ž‘์—…์‹ค/๋ฌธ์ œ ์ •๋ฆฌ

728x90
๋ฐ˜์‘ํ˜•

 

๐Ÿš€ LazyInitializationException

 

โœ” ๋ฌธ์ œ ๋ฐœ์ƒ!

 

 

 

๐Ÿ’ป Repository Code

 

๐Ÿ’ป Test Code

๋ฐ˜์‘ํ˜•

 

โœ” ๋ฌธ์ œ ์ดํ•ด

์ด๊ฒƒ์€ Review Class์˜ Member์— ๋Œ€ํ•œ Fetch ๋ฐฉ์‹์ด LAZY(์ง€์—ฐ ๋กœ๋”ฉ)์ด๊ธฐ ๋•Œ๋ฌธ์— ํ•œ ๋ฒˆ์— Review ๊ฐ์ฒด์™€ Member ๊ฐ์ฒด๋ฅผ ์กฐํšŒํ•  ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์— ๋ฐœ์ƒํ•œ Exception์ธ ๊ฒƒ์ด์—์š”.

@Transactional์„ ์ ์šฉํ•œ๋‹ค๊ณ  ํ•ด๋„ ๊ฐ Review ๊ฐ์ฒด์˜ getMember().getEmail()์„ ์ฒ˜๋ฆฌํ•  ๋•Œ๋งˆ๋‹ค Member ๊ฐ์ฒด๋ฅผ Lodingํ•ด์•ผ ํ•˜๋Š” ๋ฌธ์ œ๊ฐ€ ์žˆ๋‹ต๋‹ˆ๋‹ค!

์ด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ๋Š” ์•„๋ž˜์™€ ๊ฐ™์ด ํฌ๊ฒŒ ๋‘ ๊ฐ€์ง€๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์žˆ๋Š” ๊ฒƒ์ด์—์š”.

  1. @Query๋ฅผ ์ด์šฉํ•ด์„œ Join์ฒ˜๋ฆฌ
  2. @EntityGraph๋ฅผ ์ด์šฉํ•ด์„œ Review ๊ฐ์ฒด๋ฅผ ๊ฐ€์ ธ์˜ฌ ๋•Œ, Member ๊ฐ์ฒด Loding

 

๐Ÿ’ก ์ฐธ๊ณ  : @EntityGraph๋ž€?

@EntityGraph๋Š” Entity์˜ ํŠน์ •ํ•œ ์†์„ฑ์„ ๊ฐ™์ด Lodingํ•˜๋„๋ก ํ‘œ์‹œํ•˜๋Š” ์–ด๋…ธํ…Œ์ด์…˜.
๊ธฐ๋ณธ์ ์œผ๋กœ JPA๋ฅผ ์ด์šฉํ•˜๋Š” ๊ฒฝ์šฐ ์—ฐ๊ด€ ๊ด€๊ณ„์˜ FATCH ์†์„ฑ๊ฐ’์€ LAZY๋กœ ์ง€์ •ํ•˜๋Š” ๊ฒƒ์ด ์ผ๋ฐ˜์ ์ด๋‹ค.
@EntityGraph๋Š” ์ด๋Ÿฌํ•œ ์ƒํ™ฉ์—์„œ ํŠน์ • ๊ธฐ๋Šฅ์„ ์ˆ˜ํ–‰ํ•  ๋•Œ๋งŒ, EAGER Loding์„ ์ง€์ •ํ•  ์ˆ˜ ์žˆ๋‹ค.

@EntityGraph๋Š” attibutePaths ์†์„ฑ๊ณผ type ์†์„ฑ์„ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค.
  ใ…‡ attributePaths: Loding ์„ค์ •์„ ๋ณ€๊ฒฝํ•˜๊ณ  ์‹ถ์€ ์†์„ฑ์˜ ์ด๋ฆ„์„ ๋ฐฐ์—ด๋กœ ๋ช…์‹œ
  ใ…‡ type : @EntityGraph๋ฅผ ์–ด๋–ค ๋ฐฉ์‹์œผ๋กœ ์ ์šฉํ•  ๊ฒƒ์ธ์ง€ ์„ค์ •
  ใ…‡ FATCH ์†์„ฑ๊ฐ’์€ attributePaths์— ๋ช…์‹œํ•œ ์†์„ฑ์€ EAGER๋กœ ์ฒ˜๋ฆฌํ•˜๊ณ , ๋‚˜๋จธ์ง€๋Š” LAZY๋กœ ์ฒ˜๋ฆฌ.
  ใ…‡ LOAD ์†์„ฑ๊ฐ’์€ attributePaths์— ๋ช…์‹œํ•œ ์†์„ฑ์€ EAGER๋กœ ์ฒ˜๋ฆฌํ•˜๊ณ , ๋‚˜๋จธ์ง€๋Š” Entity Class์— ๋ช…์‹œ ๋˜๊ฑฐ๋‚˜,
      ๊ธฐ๋ณธ ๋ฐฉ์‹์œผ๋กœ ์ฒ˜๋ฆฌ

 

 

โœ” ํ•ด๊ฒฐ ๋ฐฉ์•ˆ

 

 

โœ” ์ •์ƒ ๊ธฐ๋™

 

728x90
๋ฐ˜์‘ํ˜•