์นดํ…Œ๊ณ ๋ฆฌ ์—†์Œ

Query DSL์—์„œ MySQL FIELD Function ์‚ฌ์šฉํ•˜๊ธฐ

monkeyDugi 2023. 8. 10. 21:48
๋ฐ˜์‘ํ˜•

๐Ÿ‹๐Ÿฝ ์„œ๋ก 


Query DSL์„ ์‚ฌ์šฉํ•˜๋‹ค ๋ณด๋ฉด, DB Function์„ ์ง€์›ํ•˜์ง€ ์•Š๋Š” ๊ฒƒ๋“ค์ด ๋งŽ์ด ์žˆ๋‹ค.

๋‚˜๋Š” ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์˜จ Id ๋ชฉ๋ก์„ ๊ธฐ์ค€์œผ๋กœ sortingํ•  ํ•„์š”๊ฐ€ ์žˆ์–ด์„œ field function์ด ํ•„์š”ํ–ˆ๋‹ค.

๊ทธ ๊ณผ์ •์—์„œ ๊ฒช์€ issue๋ฅผ ์‚ดํŽด๋ณด์ž.

๐Ÿ‹๐Ÿฝ ํŠธ๋Ÿฌ๋ธ” ์ŠˆํŒ…


๊ธฐ์กด ๋ฐฉ๋ฒ•

Expressions๋ฅผ ์‚ฌ์šฉํ–ˆ๋Š”๋ฐ ๋™์  ์ฟผ๋ฆฌ๋ฅผ ํ™œ์šฉํ•˜๊ธฐ ์œ„ํ•จ์ผ ๋ฟ์ด๋‹ค.

private static <T> SimpleTemplate<Integer> template(Path<T> column, List<String> ids) {
  return Expressions.simpleTemplate(Integer.class,
      "FIELD({0}, {1})", column, String.join(", ", String.join(", ", ids))
  );
}

์ฒ˜์Œ์—๋Š” ์ด ์ฝ”๋“œ์—๋Š” ๋ฌธ์ œ๊ฐ€ ์žˆ๋‹ค.

์ฟผ๋ฆฌ ๋กœ๊ทธ๋กœ๋Š” ์ด์ƒ์—†์ด ๋นŒ๋“œ๊ฐ€ ๋œ ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ์—ˆ๋‹ค.

ํ•ด๋‹น ์ฟผ๋ฆฌ๋ฅผ ๋ณต์‚ฌํ•˜์—ฌ ๋Œ๋ ค๋ด๋„ ์ž˜ ๋‚˜์™”๋‹ค.

ํ•˜์ง€๋งŒ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์„ ํ†ตํ•˜๋ฉด ์ •๋ ฌ์ด ๋˜์ง€ ์•Š์•˜๋‹ค.

๋ฐ”๋กœ String.join()์˜ ๋ฌธ์ œ์ด๋‹ค.

String.join()์˜ ๊ฒฐ๊ณผ๋Š” FIELD(id, 1, 2, 3)์œผ๋กœ ์ƒ์„ฑ๋œ ๊ฒƒ์ด ์•„๋‹ˆ๊ณ , FIELD(id, โ€˜1, 2, 3โ€™)์œผ๋กœ ์ƒ์„ฑ๋œ ๊ฒƒ์ด๋‹ค.

String ํƒ€์ž…์ด๊ธฐ ๋•Œ๋ฌธ์— โ€˜โ€™๊ฐ€ ๋ถ™๊ฒŒ ๋˜์—ˆ๋‹ค.

๊ฐœ์„  ๋ฐฉ๋ฒ•

Collection ์ž์ฒด๋ฅผ ๋งˆ์ง€๋ง‰ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋„˜๊ธฐ๋„๋ก ๋ณ€๊ฒฝํ–ˆ๋‹ค.

๊ฒฐ๊ณผ๋Š” FIELD(id, 1, 2, 3)์™€ ๊ฐ™์ด ์ƒ์„ฑ๋œ๋‹ค.

private static <T> SimpleTemplate<Integer> template(Path<T> column, List<String> ids) {
  return Expressions.template(Integer.class, "FIELD({0}, {1})", column, ids);
}

์ฒ˜์Œ์—๋Š” biding log๊ฐ€ [1, 2, 3] ์ด๋ ‡๊ฒŒ ๋‚˜์™€์„œ String์ž„์—๋„ โ€˜โ€™๋กœ ๊ฐ์‹ธ์ง„๋‹ค๋Š” ๊ฒƒ์„ ์ƒ๊ฐํ•˜์ง€ ๋ชปํ–ˆ๋‹ค.

๋ฐ˜์‘ํ˜•