Mapping an enum data type in postgres to an enum in Java with JPA and Hibernate

Adeogo Oladipo
4 min readApr 10, 2022

Let’s say you created a custom type in postgreSQL, Let’s call it record_type. It’s an enum defined as follows: receipt, invoice, permit.

Then we subsequently use this custom type in a table called records with the following columns: id of type big int, nameof type character varying, type of type record_typeand issuer_name of type character varying.

How do you map this records table to an entity class in your Spring Boot Application?

This was the task I was faced with some weeks ago. It took some digging, reading some interesting articles and learning much more about Hibernate before the task was completed. I decided to write this article to help someone facing a similar issue or roadblock.

Project Structure

We will be using a demo project to test the changes we make. It will contain Controller, Service, Repository, Entity, and Dto classes.

Making Read operations for the table

If all your operations with the Entity are all Read operations, then using the type String to map the custom type is sufficient.

Making Write operations for the table

If you tried to save the entity with the current mapping, you’ll get this error:

First idea tried:

Just create an Enum type in the Entity class and use it as the datatype of the column we want to get.

This doesn’t work, because it maps the int value of the enum and not the actual value of it. So you get this error:

Second idea:

After some Stackoverflow searches, the common solution was to combine the first idea and also annotate the field as Enumerated. https://stackoverflow.com/questions/16140282/jpa-enumerated-types-mapping-best-approach

Third idea:

Using Embedded and Embeddable. This also falls short during the write operation.

The correct way:

First we create a type definition for the PostgreSQL Enum. Then use the type definition in our entity like so.

Conclusion

While this article, goes through some wrong ideas before showing the correct one, the hope is to show other ways that could have been applied to fix some other forms of the same problem. So if in your case the correct answer is not particularly suitable, other variants of all the ideas posed here should work.

--

--

Adeogo Oladipo

Co-Founder and CTO @DokitariUG. A Strong believer in the Potential in Each Human.