Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to persist an enum as string in Hibernate 6 Spring Boot 3 without using hibernate-types-62 in PostgreSQL

With the following postgresql database components and the removal of the @Type and @Typedef annotations in Spring Boot 3 (Hibernate 6), how do I persist an enum as a String in the database when the database also uses an Enum type for that column.

PG Database example:

CREATE TYPE TEST_TYPE AS ENUM ('TESTA','TESTB');

CREATE TABLE test_table (
    id     INT           NOT NULL PRIMARY KEY,
    type   TEST_TYPE     NOT NULL
);

with the following Entity

@Entity
@Table(name = "test_table")
public class TestTableEntity
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Enumerated(EnumType.STRING)
    @Column(name = "type")
    private TestType tenantId;
}

This fails with an error because it attempts to persist it as a string instead of the enum type.

All other resources reference using the hypersistence-utils library, hibernate-types-62. However, I shouldn't need to be dependent on an external utils library.

The other solutions are clunky and require implementing a new hierarchy just for enums.

What is the simpler solution for PostgreSQL?

like image 883
StevenPG Avatar asked Oct 12 '25 12:10

StevenPG


1 Answers

You can use ColumnTransformers to alter the SQL generated by Hibernate.

This is a working example of the entity:

@Entity
@Table(name = "test_table")
public class TestTableEntity
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Enumerated(EnumType.STRING)
    @Column(name = "type")
    @ColumnTransformer(write = "?::TEST_TYPE")
    private TestType tenantId;
}

If it's part of a different schema, you may need to do

@ColumnTransformer(write = "?::other_table.TEST_TYPE")

If you inspect the SQL that is generated, this will use the @Enumerated annotation to pass the TestType as a string. The ColumnTransformer will then add the cast in for writing, allowing the DB's insert/update query to provide the correct parameter type for the intended column.

On the way back out, since we have @Enumerated configured to use String, Hibernate will figure out based on the stored String, which Enum to select and return.

This is a simple one-liner that doesn't require writing a custom UserType or pulling in a library just to support Enums.

like image 132
StevenPG Avatar answered Oct 16 '25 09:10

StevenPG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!