Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Browser testing is essential if you have a website or web applications that users interact with. Manual testing can be very helpful to an extent, but given the multiple browsers available, not to mention versions and operating system, testing everything manually becomes time-consuming and repetitive.

To help automate this process, Selenium is a popular choice for developers, as an open-source tool with a large and active community. What's more, we can further scale our automation testing by running on theLambdaTest cloud-based testing platform.

Read more through our step-by-step tutorial on how to set up Selenium tests with Java and run them on LambdaTest:

>> Automated Browser Testing With Selenium

Partner – Orkes – NPI EA (cat=Java)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LSD – NPI (cat=JPA)
announcement - icon

Get started with Spring Data JPA through the reference Learn Spring Data JPA:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)