1. Introduction

In this tutorial, we’ll explore the concepts of Java enums, JPA, and PostgreSQL enums, and learn how to use them together to create a seamless mapping between Java enums and PostgreSQL enums.

2. Java enum

Java enums are a special type of class that represents a fixed number of constants. Enums are used to define a set of named values that have underlying types, such as strings or integers. Enums are useful when we need to define a set of named values that have a specific meaning in our application.

Here is an example of a Java enum:

public enum OrderStatus {
    PENDING, IN_PROGRESS, COMPLETED, CANCELED
}

In this example, the OrderStatus enum defines four constants. These constants can be used in our application to represent the status of an order.

3. Using @Enumerated Annotation

When using Java enums with JPA, we need to annotate the enum field with @Enumerated to specify how the enum value should be stored in the database.

First, we define an entity class named CustomerOrder annotated with @Entity to mark it for JPA persistence:

@Entity
public class CustomerOrder {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Enumerated() 
    private OrderStatus status;

    // ... other fields and methods
}

By default, JPA stores the enum value as an integer, representing the ordinal position of the enum constant. For example, if we have an enum OrderStatus with values PENDING, IN_PROGRESS, COMPLETED, and CANCELED, the default behavior would store them as integers 0, 1, 2 and 3, respectively. The resulting database table would have a status column of type smallint, with values 0 to 3:

create table customer_order (
    id bigserial not null,
    status smallint check (status between 0 and 3),
    primary key (id)
);

However, this default behavior can lead to problems if we change the order of the enum constants in our Java code. For example, if we swap the order of IN_PROGRESS and PENDING, the database values would still be 0, 1, 2 and 3, but they would no longer match the updated enum order. This can lead to inconsistencies and errors in our application.

To avoid this problem, we can use EnumType.STRING to store the enum value as a string in the database. This approach ensures that the enum value is stored in a human-readable format, and we can change the order of the enum constants without affecting the database values:

@Enumerated(EnumType.STRING)
private OrderStatus status;

This instructs JPA to store the string representation of the OrderStatus enum value (e.g., “PENDING“) in the database instead of the ordinal position (integer index). The resulting database table would have a status column of type varchar that can hold the specific string values defined in our enum:

create table customer_order (
    id bigint not null,
    status varchar(16) check (status in ('PENDING','IN_PROGRESS', 'COMPLETED', 'CANCELLED')),
    primary key (id)
);

4. The Challenge of Mapping Java Enums to PostgreSQL Enums

Mapping Java enums to PostgreSQL enums can be challenging due to differences in their handling and capabilities. Even with the EnumType.STRING, JPA still doesn’t know how to map the Java enum to the PostgreSQL enum. To demonstrate the problem, let’s create a PostgreSQL enum type:

CREATE TYPE order_status AS ENUM ('PENDING', 'IN_PROGRESS', 'COMPLETED', 'CANCELED');

Next, we create a table that uses the PostgreSQL enum type:

CREATE TABLE customer_order (
    id BIGINT NOT NULL,
    status order_status,
    PRIMARY KEY (id)
);

We’ve updated the status column to use the PostgreSQL enum type order_status. Now, let’s try to insert some data into the table:

CustomerOrder order = new CustomerOrder();
order.setStatus(OrderStatus.PENDING);
session.save(order);

However, when we try to insert the data, we’ll get an exception:

org.hibernate.exception.SQLGrammarException: could not execute statement 
  [ERROR: column "status" is of type order_status but expression is of type character varying

The SQLGrammarException occurs because JPA doesn’t know how to map the Java enum OrderStatus to the PostgreSQL enum order_status.

5. Using @Type Annotation

In Hibernate 5, we can leverage the Hypersistence Utils library to address this challenge. This library provides additional types, including support for PostgreSQL enums.

First, we need to add the Hypersistence Utils dependency to our pom.xml:

<dependency>
    <groupId>io.hypersistence</groupId>
    <artifactId>hypersistence-utils-hibernate-55</artifactId>
    <version>3.7.0</version>
</dependency>

The Hypersistence Utils library includes a PostgreSQLEnumType class that handles the conversion between Java enums and PostgreSQL enum types. We’ll use this class as our custom type handler.

Next, we can annotate the enum field using the @Type annotation and define the custom type handler in our entity class:

@Entity
@TypeDef(
    name = "pgsql_enum",
    typeClass = PostgreSQLEnumType.class
)
public class CustomerOrder {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Long id;

    @Enumerated(EnumType.STRING)
    @Column(columnDefinition = "order_status")
    @Type(type = "pgsql_enum")
    private OrderStatus status;

    // ... other fields and methods
}

By following these steps, we can effectively map PostgreSQL enum types to Java enums in Hibernate 5.

6. Using PostgreSQLEnumJdbcType

In Hibernate 6, we can use the @JdbcType annotation directly on our enum field to specify a custom JDBC type handler. This annotation allows us to define a custom JdbcType class to handle the mapping between our Java enum type and the corresponding JDBC type.

Here’s how we can use @JdbcType in our CustomerOrder entity:

@Enumerated(EnumType.STRING)
@JdbcType(type = PostgreSQLEnumJdbcType.class)
private OrderStatus status;

We’re specifying the PostgreSQLEnumJdbcType class as the custom type handler. This class is part of Hibernate 6 and is responsible for handling the conversion between the Java enum string and the PostgreSQL enum type.

When we persist an OrderStatus object (e.g., order.setStatus(OrderStatus.PENDING)), Hibernate first converts the enum value to its string representation (“PENDING“). Then, the PostgreSQLEnumJdbcType class takes the string value (“PENDING“) and converts it into a format suitable for the PostgreSQL enum type. The converted value is then passed to the database for storage in the order_status column.

7. Inserting Enum Values Using Native Query

When using a native query to insert data into a PostgreSQL table, the type of the data being inserted must match the column type. For an enum type column, PostgreSQL expects the value to be of the enum type, not just a plain string. 

Let’s try using a native query without casting:

String sql = "INSERT INTO customer_order (status) VALUES (:status)";
Query query = session.createNativeQuery(sql);
query.setParameter("status", OrderStatus.COMPLETED); // Use the string representation of the enum

We get the following error:

org.postgresql.util.PSQLException: ERROR: column "status" is of type order_status but expression is of type character varying

This error occurs because PostgreSQL expects the value to be of type order_status but receives a character varying instead. To resolve this, we explicitly cast the value to the enum type in the native query:

String sql = "INSERT INTO customer_order (status) VALUES (CAST(:status AS order_status))";
Query query = session.createNativeQuery(sql);
query.setParameter("status", OrderStatus.COMPLETED);

The CAST(:status AS order_status) part in the SQL statement ensures that the string value “COMPLETED” is explicitly cast to the order_status enum type in PostgreSQL.

8. Conclusion

In this article, we’ve explored how to map between Java enums and PostgreSQL enums using JPA. By using PostgreSQLEnumJdbcType we ensure seamless integration between Java enum and PostgreSQL enum.

As always, the source code for the examples is available over on GitHub. The source code for the Hibernate 5 examples is available over on GitHub.