postgres ๋ฐ jsonb์ ํจ๊ป jdbi๋ฅผ ์ฌ์ฉํ์ฌ ๋ค์๊ณผ ๊ฐ์ ์ฟผ๋ฆฌ๋ฅผ ์์ฑํ๋ ค๊ณ ํฉ๋๋ค.
select id, data from some_table where data ? :key
๋ถํํ๋ jdbi๋ ์ด ๋ฌผ์ํ๋ฅผ ๋ณ์์ ์๋ฆฌ ํ์์๋ก ํด์ํฉ๋๋ค. postgres ๋ฌผ์ํ ์ฐ์ฐ์๋ฅผ ์ฌ์ฉํ ์ ์๋๋ก ๋ฌผ์ํ๋ฅผ ์ด๋ป๊ฒ ๋ฒ์ด๋ ์ ์์ต๋๊น?
๋ฐฑ์ฌ๋์ \?
๋ฅผ ์ฌ์ฉํด ๋ณด์
จ์ต๋๊น?
๊ทธ๋, ๋ด๊ฐ ๊ทธ๊ฑธ ์ธ๊ธํ์ด์ผ ํ๋ ๊ฒ ๊ฐ์. ๊ทธ๊ฒ์ด ๋์ ์ฒซ ๋ฒ์งธ ๋ณธ๋ฅ์ด์๋ค. ํ์ง๋ง ์ฌ์ ํ ์ค๋ฅ๊ฐ ๋ฐ์ํฉ๋๋ค.
Exception in thread "main" org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException: org.postgresql.util.PSQLException: No value specified for parameter 2. [statement:"select id, createdDate, data from something where data \? ?", located:"select id, createdDate, data from something where data \? ?", rewritten:"select id, createdDate, data from something where data ? ?", arguments:{ positional:{0:'pattern'}, named:{}, finder:[]}]
at org.skife.jdbi.v2.SQLStatement.internalExecute(SQLStatement.java:1334)
at org.skife.jdbi.v2.Query.fold(Query.java:173)
at org.skife.jdbi.v2.Query.list(Query.java:82)
at org.skife.jdbi.v2.Query.list(Query.java:75)
at com.ngc.vault.eventer.Query.hasKey(Query.java:45)
at com.ngc.vault.eventer.Main.main(Main.java:34)
Caused by: org.postgresql.util.PSQLException: No value specified for parameter 2.
at org.postgresql.core.v3.SimpleParameterList.checkAllParametersSet(SimpleParameterList.java:228)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:163)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:615)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:465)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:458)
at org.skife.jdbi.v2.SQLStatement.internalExecute(SQLStatement.java:1328)
... 5 more
์ด๊ฒ์ jdbc์ ์ ์คํธ๋ฆผ ๋ฌธ์ ์ ๋๋ค. ๊ทธ๋ค์ ๊ทธ๊ฒ์ ํ์ถํ๋ ๋ฐฉ๋ฒ์ ๊ตฌํํ์ต๋๋ค. ๋น์ ์ ??์ ์ฌ์ฉํด์ผํฉ๋๋ค. ์ด๋ ๊ฒ:
select id, data from some_table where data ?? :key
ํฌ์คํธ๊ทธ๋ ์ค ์ฟผ๋ฆฌ
SELECT json_data FROM employee where json_data -> 'employee' @> '{"name":"Aman"}'
์์ ์ฟผ๋ฆฌ๋ postgres์์ ์คํํ ๋ ์ ์๋ํฉ๋๋ค. ๊ทธ๋ฌ๋ jdbctemplate์ผ๋ก ์คํํ๋ฉด ์ค๋ฅ๊ฐ ๋ฐ์ํฉ๋๋ค.
์๋ฐ ์ฝ๋
String sql="SELECT json_data FROM employee where json_data -> 'employee' @> '{\"name\":\"?\"}'";
List<Map<String, Object>> emp = jdbcTemplate.queryForList(sql,param);
์ฝ๋์ ๋ง์ง๋ง ์ค์ ๋ง๋๋ฉด ์ค๋ฅ๊ฐ ๋ฐ์ํฉ๋๋ค. - ์ด ์ธ๋ฑ์ค๊ฐ ๋ฒ์๋ฅผ ๋ฒ์ด๋ฌ์ต๋๋ค: 1, ์ด ์: 0.; ์ค์ฒฉ ์์ธ๋ org.postgresql.util.PSQLException์ ๋๋ค.
'?'๋ฅผ ๋์ฒดํ ์ ์์ต๋๋ค. ์๋ฆฌ ํ์์.
๊ทธ๊ฒ์ JDBC ์ฌ์์ ๋ฐ๋ฅธ ๊ฒ์
๋๋ค. ?
๋ง์ปค๋ ๋ฌธ์์ด ๋ฆฌํฐ๋ด ๋ด์์ ๋งค๊ฐ๋ณ์๋ก ์ธ์๋์ง ์์ต๋๋ค.
๋งค๊ฐ๋ณ์๋ฅผ ํด๋น JSON ๋ฌธ์์ด๋ก ๋ณด๊ฐํด์ผ ํ๋ ๊ฒฝ์ฐ ์ฐ๊ฒฐ์ ์ฌ์ฉํ์ญ์์ค. Postgres ์ฐ๊ฒฐ ๊ตฌ๋ฌธ์ ์ฌ์ฉํ๋ฉด ์ฟผ๋ฆฌ๋ ๋ค์๊ณผ ๊ฐ์ต๋๋ค.
SELECT json_data
FROM employee
WHERE json_data -> 'employee' @> ('{"name": "' || ? || '"}')
๋ํ ์ด๊ฒ์ JdbcTemplate์ด ์๋๋ผ Jdbi ํ๋ก์ ํธ๋ผ๋ ์ ์ ์ ์ํ์ญ์์ค. :)
๊ฐ์ฅ ์ ์ฉํ ๋๊ธ
์ด๊ฒ์ jdbc์ ์ ์คํธ๋ฆผ ๋ฌธ์ ์ ๋๋ค. ๊ทธ๋ค์ ๊ทธ๊ฒ์ ํ์ถํ๋ ๋ฐฉ๋ฒ์ ๊ตฌํํ์ต๋๋ค. ๋น์ ์ ??์ ์ฌ์ฉํด์ผํฉ๋๋ค. ์ด๋ ๊ฒ: