27 July, 2009

JDBC: Postgres enums and prepared statements

There is simple way how to map Java enums to PostgreSQL enums via JDBC's prepared statements.

For example we have these PostgreSQL enum and table definitions:

CREATE TYPE log_level AS ENUM ('INFO', 'WARN', 'ERROR');

CREATE TABLE logs (
id SERIAL PRIMARY KEY,
message VARCHAR(255) NOT NULL,
level log_level NOT NULL,
);


And Java enum:

public enum LogLevel {
INFO, WARN, ERROR
}


This form of prepared statement should work:

LogLevel logLevel = LogLevel.INFO;
PreparedStatement sql = conn.prepareStatement("INSERT INTO logs (message, log_level) VALUES (?, ?::log_level)");
sql.setString(1, "Hello world");
//sql.setString(2, "INFO");
sql.setString(2, logLevel.name());

1 comment:

Unknown said...

Thank you, Alex! Your snippet made my day! :^]