Postgres ENUM, Java ENUM and JPA

We have a postgres DB with postgres enums on one side and Java enums on the other. The question is – how to combine them together over JPA?

The problem is in JDBC driver which returns Postgres enums as an instance of type PGObject. The type property of this has the name of postgres enum, and the value property its value (the ordinal is not stored however, so technically it’s not an enum anymore and possibly completely useless because of this).

So if your Postgres type definition looks like this:

Then the resultset will contain a PGObject with type “direction” and value “from” for a column having this enum type and a row with the value “from”.

Next thing to do is writing some interceptor code that sits between the spot where JPA reads from the raw resultset and sets the value on your entity. E.g. suppose you had the following in Java:

    • Enum:

    • And entity:

Type and TypeDef annotations allows you to map type names to Hibernate UserType. Now we should supply an instance of UserType that does the actual conversion:

The nullSafeGet method is used to retrieve the mapped class from the result set and nullSafeSet method is used to store the mapped class in the database.