Search code examples
postgresqlspring-jdbcjdbctemplate

JdbcTemplate query returns BadSqlGrammarException


Postgres db:

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');

when I am trying to execute the method:

        Map<String, Object> data = jdbcTemplate.queryForMap("select * from payment_request_statuses where pr_status_name = ?", new Object[]{"CREATED"});

I am getting the following error:

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.

Seems, jdbcTemplate for some reason is not able transform/match String to db Enum object that is surprise for me.

How can I fix it?


Solution

  • You need to cast from String to Enum in SQL.

    Map<String, Object> data = jdbcTemplate.queryForMap("select * from payment_request_statuses where pr_status_name = ?::pr_status_name", new Object[]{"CREATED"});