Back-end/JPA

[JPA] native query ์‚ฌ์šฉ ์‹œ enum์„ ๋ณ€์ˆ˜๋กœ ํ•˜๊ธฐ ( SpEL expression )

 

๐Ÿ™‚ Native Query ๋ž€?

JPQL์„ ์‚ฌ์šฉํ•ด์„œ ์ฟผ๋ฆฌ ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ MySQL๊ณผ ๋น„์Šทํ•œ ํ˜•์‹์œผ๋กœ ์ฟผ๋ฆฌ๋ฅผ ๋งŒ๋“ค์–ด ์ ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

๊ทธ๋Ÿฌ๋‚˜, JPQL์—์„œ๋Š” ํ‘œ์ค€ SQL์˜ ๋Œ€๋ถ€๋ถ„์˜ ๊ธฐ๋Šฅ์„ ์ง€์›ํ•˜์ง€๋งŒ, ์ง€์›ํ•˜์ง€ ๋ชปํ•˜๋Š” ๋ฌธ๋ฒ•๋“ค๋„ ์กด์žฌํ•œ๋‹ค. ( ex. sub query )

์ด๋•Œ Native Query๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด JPQL์—์„œ ์ง€์›ํ•˜์ง€ ๋ชปํ•˜๋Š” ๋ฌธ๋ฒ•๋“ค์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

 

๐Ÿ™‚ Native Query ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•

//-- JPQL
@Query(value="SELECT M from Member M" )

//-- Native Query
@Query(value="SELECT * from Member m", nativeQuery= true )

 

๐Ÿ™‚ Native Query์—์„œ @Param์— Enum์„ ๋„ฃ๋Š” ๋ฐฉ๋ฒ•?

JPQL์„ ์‚ฌ์šฉํ•˜๋ฉด, Java์— Enum ํƒ€์ž…์„ ์•„๋ž˜์™€ ๊ฐ™์ด ์ฟผ๋ฆฌ ๋ณ€์ˆ˜๋กœ ๋„ฃ์„ ์ˆ˜ ์žˆ๋‹ค.

@Query(value="SELECT M FROM MEMBER M WHERE TYPE = (:type) )
fun getMemberByType(@Param type MemberType) 

enum class MemberType(
    MASTER,
    NORMAL,
)

๊ทธ๋Ÿฌ๋‚˜ NativeQuery์—์„œ Enumํƒ€์ž…์„ ์‚ฌ์šฉํ•ด์„œ ์œ„์™€ ๊ฐ™์ด ๋ณ€์ˆ˜๋กœ ๋„ฃ์œผ๋ฉด,,, ์—๋Ÿฌ๊ฐ€ ๋‚œ๋‹ค. ( String์œผ๋กœ ๋„ฃ์–ด์•ผ ํ•˜๋„๋ก.. )

์–ด๋–ป๊ฒŒ ํ•˜๋ฉด String์œผ๋กœ ๋ณ€๊ฒฝํ•ด์•ผํ•˜๋Š” ๋ฒˆ๊ฑฐ๋กœ์›€์„ ํ•ด์†Œ์‹œํ‚ค๊ธฐ ์œ„ํ•ด, ๊ทธ๋Œ€๋กœ Enum์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์„๊นŒ?

ํ•ด๊ฒฐ์ฑ…์„ SpEL expression ์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

 

 

๐Ÿ™‚ SpEL (Spring Expression Language)์ด๋ž€?

- ์Šคํ”„๋ง ํ”„๋กœ์ ํŠธ์—์„œ ๋Ÿฐํƒ€์ž„์— ์ฟผ๋ฆฌ๋ฅผ ์ง€์›ํ•˜์—ฌ ๊ฐ์ฒด๋ฅผ ์กฐ์ž‘ํ•  ์ˆ˜ ์žˆ๋Š” ํ‘œํ˜„์‹

( ์ฐธ๊ณ  : https://atoz-develop.tistory.com/entry/Spring-SpEL-Spring-Expression-Language )

 

 

๐Ÿ™‚ SpEL์„ ์‚ฌ์šฉํ•ด์„œ Native Query์—์„œ Enum ํƒ€์ž… ์‚ฌ์šฉํ•˜๊ธฐ

 

- Enum์˜ ํ•œ ๋ณ€์ˆ˜๋งŒ ์‚ฌ์šฉํ•˜๊ธฐ
#{#๋ณ€์ˆ˜.name()}

@Query(value="SELECT * FROM member m WHERE m.type = #{#type.name()} )
fun getMemberByType(@Param("type") type MemberType) 

enum class MemberType(
    MASTER,
    NORMAL,
)

 

- Enum์„ Collection(List, Set์œผ๋กœ ์‚ฌ์šฉํ•˜๊ธฐ
#{#๋ณ€์ˆ˜.![name()]}

@Query(value="SELECT * FROM member m WHERE m.type in #{#types.![name()]} )
fun getMemberInTypes(@Param("types") types Set<MemberType>) 

enum class MemberType(
    MASTER,
    NORMAL,
)
๋ฐ˜์‘ํ˜•

'Back-end > JPA' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[JPA] JPA native query ์‚ฌ์šฉ์‹œ dto mapping  (0) 2022.02.06
[JPA] JPA (Java Persistence API)๋ž€?  (0) 2020.09.08