Skip to content

[refactor] Spring data JPA - findBy vs getReferenceByย #106

Description

@HanKwanJin

๐Ÿค” ์ฝ”๋“œ ๊ฐœ์„  ํ•„์š”์„ฑ

์ €ํฌ ์ฝ”๋“œ์—์„œ๋Š” findBy ๋งŒ์„ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์กฐํšŒ์—๋Š” findBy๋ฅผ ์“ฐ๋˜ ์ €์žฅ, ์‚ญ์ œ, ์ˆ˜์ •์— ์‚ฌ์šฉ๋˜๋Š” findBy ๋ฉ”์†Œ๋“œ๋“ค์€ getReferenceBy๋กœ ์ˆ˜์ •ํ•˜๋ฉด ์–ด๋–จ๊นŒํ•ฉ๋‹ˆ๋‹ค. ์ด์œ ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

findBy์™€ getReferenceBy ๋‘˜์˜ ๋Œ€ํ‘œ์ ์ธ ์ฐจ์ด์ ์œผ๋กœ๋Š” 2๊ฐ€์ง€๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค.

  1. 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.

  1. findBy์™€ getReferenceBy๋Š” Entity๋ฅผ ์ฐพ์•„์˜ค๋Š”๊ฑด ๋™์ผํ•˜์ง€๋งŒ ๋™์ž‘ ๋ฐฉ์‹์ด ๋‹ค๋ฆ…๋‹ˆ๋‹ค. getReferenceBy๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด ์ฐธ์กฐ๊ฐ’๋งŒ ๊ฐ€์ ธ์˜จ ํ›„์— ์กฐํšŒ๋œ Entity์˜ ๋‚ด๋ถ€์— ๊ฐ’์ด ํ•„์š”ํ•  ๋•Œ DB๋ฅผ ์กฐํšŒํ•˜๋Š” lazy loading์œผ๋กœ ๋™์ž‘ํ•ฉ๋‹ˆ๋‹ค. ์ฆ‰, getReferenceBy๋ฅผ ๋‚ด๋ถ€์˜ ๊ฐ’์„ ํ•„์š”๋กœ ํ•˜์ง€ ์•Š๋Š” ์ €์žฅ, ์‚ญ์ œ, ์ˆ˜์ •์— ์‚ฌ์šฉํ•˜๊ณ  ๋‚ด๋ถ€์˜ ๊ฐ’์ด ํ•„์š”ํ•œ ์กฐํšŒ์— ๊ฒฝ์šฐ findBy๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด lazy loading์œผ๋กœ ์ธํ•ด ์กฐ๊ธˆ์ด๋ผ๋„ ์„ฑ๋Šฅ ๊ฐœ์„ ์ด ๋  ๊ฒƒ์ด๋ผ๊ณ  ์˜ˆ์ƒ๋ฉ๋‹ˆ๋‹ค.

๐Ÿ’ก ์ฐธ๊ณ ์ž๋ฃŒ

[findBy vs getReferenceBy]

[ํ”„๋ก์‹œ lazy loading]

Metadata

Metadata

Assignees

Labels

Type

No type
No fields configured for issues without a type.

Projects

Status
No status

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions