๐ค ์ฝ๋ ๊ฐ์ ํ์์ฑ
์ ํฌ ์ฝ๋์์๋ findBy ๋ง์ ์ฌ์ฉํ๊ณ ์์ต๋๋ค. ์กฐํ์๋ findBy๋ฅผ ์ฐ๋ ์ ์ฅ, ์ญ์ , ์์ ์ ์ฌ์ฉ๋๋ findBy ๋ฉ์๋๋ค์ getReferenceBy๋ก ์์ ํ๋ฉด ์ด๋จ๊นํฉ๋๋ค. ์ด์ ๋ ๋ค์๊ณผ ๊ฐ์ต๋๋ค.
findBy์ getReferenceBy ๋์ ๋ํ์ ์ธ ์ฐจ์ด์ ์ผ๋ก๋ 2๊ฐ์ง๊ฐ ์์ต๋๋ค.
- findBy๋ ๋งค๊ฐ๋ณ์๋ก ์ ๋ฌ๋ ๊ฐ์ ํด๋นํ๋ Entity๋ฅผ ๋ฐํํ๊ฑฐ๋, ํด๋นํ๋ Entity๊ฐ ์์ ๊ฒฝ์ฐ
Optional.empty()๋ฅผ ๋ฐํํฉ๋๋ค. ์ฆ, ํ์ ๊ฒฐ๊ณผ๊ฐ ์๋๋ผ๋ ๋ด๋ถ์์ ์์ธ๋ฅผ ๋ฐ์์ํค๊ธฐ ์์ต๋๋ค. ๋ฐ๋ฉด์, getReference๋ ๋งค๊ฐ๋ณ์๋ก ์ ๋ฌ๋ ๊ฐ์ ํด๋นํ๋ Entity๊ฐ ์์ผ๋ฉด ๋ด๋ถ์์ EntityNotFoundException ์์ธ๋ฅผ ๋ฐ์์ํต๋๋ค. ๊ทธ๋ฌ๋ฏ๋ก try-catch๋ก ์์ธ๋ฅผ ์ฒ๋ฆฌํด์ค์ผํ๋ ์ฝ๋๊ฐ ์ถ๊ฐ๋๊ธดํฉ๋๋ค.
Returns a reference to the entity with the given identifier.
Depending on how the JPA persistence provider is implemented
this is very likely to always return an instance and throw an EntityNotFoundException on first access.
Some of them will reject invalid identifiers immediately.
- findBy์ getReferenceBy๋ Entity๋ฅผ ์ฐพ์์ค๋๊ฑด ๋์ผํ์ง๋ง ๋์ ๋ฐฉ์์ด ๋ค๋ฆ
๋๋ค. getReferenceBy๋ฅผ ํธ์ถํ๋ฉด ์ฐธ์กฐ๊ฐ๋ง ๊ฐ์ ธ์จ ํ์ ์กฐํ๋ Entity์ ๋ด๋ถ์ ๊ฐ์ด ํ์ํ ๋ DB๋ฅผ ์กฐํํ๋ lazy loading์ผ๋ก ๋์ํฉ๋๋ค. ์ฆ, getReferenceBy๋ฅผ ๋ด๋ถ์ ๊ฐ์ ํ์๋ก ํ์ง ์๋ ์ ์ฅ, ์ญ์ , ์์ ์ ์ฌ์ฉํ๊ณ ๋ด๋ถ์ ๊ฐ์ด ํ์ํ ์กฐํ์ ๊ฒฝ์ฐ findBy๋ฅผ ์ฌ์ฉํ๋ฉด lazy loading์ผ๋ก ์ธํด ์กฐ๊ธ์ด๋ผ๋ ์ฑ๋ฅ ๊ฐ์ ์ด ๋ ๊ฒ์ด๋ผ๊ณ ์์๋ฉ๋๋ค.
๐ก ์ฐธ๊ณ ์๋ฃ
[findBy vs getReferenceBy]
[ํ๋ก์ lazy loading]
๐ค ์ฝ๋ ๊ฐ์ ํ์์ฑ
์ ํฌ ์ฝ๋์์๋ findBy ๋ง์ ์ฌ์ฉํ๊ณ ์์ต๋๋ค. ์กฐํ์๋ findBy๋ฅผ ์ฐ๋ ์ ์ฅ, ์ญ์ , ์์ ์ ์ฌ์ฉ๋๋ findBy ๋ฉ์๋๋ค์ getReferenceBy๋ก ์์ ํ๋ฉด ์ด๋จ๊นํฉ๋๋ค. ์ด์ ๋ ๋ค์๊ณผ ๊ฐ์ต๋๋ค.
findBy์ getReferenceBy ๋์ ๋ํ์ ์ธ ์ฐจ์ด์ ์ผ๋ก๋ 2๊ฐ์ง๊ฐ ์์ต๋๋ค.
Optional.empty()๋ฅผ ๋ฐํํฉ๋๋ค. ์ฆ, ํ์ ๊ฒฐ๊ณผ๊ฐ ์๋๋ผ๋ ๋ด๋ถ์์ ์์ธ๋ฅผ ๋ฐ์์ํค๊ธฐ ์์ต๋๋ค. ๋ฐ๋ฉด์, getReference๋ ๋งค๊ฐ๋ณ์๋ก ์ ๋ฌ๋ ๊ฐ์ ํด๋นํ๋ Entity๊ฐ ์์ผ๋ฉด ๋ด๋ถ์์EntityNotFoundException์์ธ๋ฅผ ๋ฐ์์ํต๋๋ค. ๊ทธ๋ฌ๋ฏ๋ก try-catch๋ก ์์ธ๋ฅผ ์ฒ๋ฆฌํด์ค์ผํ๋ ์ฝ๋๊ฐ ์ถ๊ฐ๋๊ธดํฉ๋๋ค.๐ก ์ฐธ๊ณ ์๋ฃ
[findBy vs getReferenceBy]
[ํ๋ก์ lazy loading]