Postgres数据库:
CREATE TYPE pr_status_name AS ENUM ('CREATED', 'SUCCESS', 'FAILED');
create table payment_request_statuses(
status_id serial PRIMARY KEY,
pr_status_name pr_status_name NOT NULL
);
INSERT INTO payment_request_statuses(pr_status_name) VALUES ('CREATED');
INSERT INTO payment_request_statuses(pr_status_name) VALUES ('SUCCESS');
INSERT INTO payment_request_statuses(pr_status_name) VALUES ('FAILED');
当我尝试执行该方法时:
Map<String, Object> data = jdbcTemplate.queryForMap("select * from payment_request_statuses where pr_status_name = ?", new Object[]{"CREATED"});
我收到以下错误:
rg.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [select * from payment_request_statuses where pr_status_name = ?]; nested exception is org.postgresql.util.PSQLException: ERROR: operator does not exist: pr_status_name = character varying
Hint: No operator matches the given name and argument types. You might need to add explicit type casts.
似乎,出于某种原因,jdbcTemplate无法将字符串转换/匹配到db Enum对象,这令我感到惊讶。
我该如何解决?
您需要在SQL中从String强制转换为Enum。
Map<String, Object> data = jdbcTemplate.queryForMap("select * from payment_request_statuses where pr_status_name = ?::pr_status_name", new Object[]{"CREATED"});