Search code examples
javahibernateenumshibernate-types

Store Java enums in Postgresql and Hibernate 6 using hbm.xml


I am unable to figure out how to store a Java Enum using a Postgresql Enum Type with Hibernate 6 and the legacy hbm.xml.

With Hibernate 5, I used to use the hiberate-types project with following XML:

<property name="type" column="Type" access="field">
        <type name="com.vladmihalcea.hibernate.type.basic.PostgreSQLEnumType">
            <param name="enumClass">"my-java-enum-type"</param>
            <param name="useNamed">true</param>
        </type>
    </property>

But, this is not working with Hibernate 6 anymore. There is a documentation from the package's Author how to use it with annotations, but currently it is not feasible for us to switch to annotations (https://vladmihalcea.com/the-best-way-to-map-an-enum-type-with-jpa-and-hibernate/).

I would be glad if anyone could give a hint.


Solution

  • I solved the issue by writing my own type:

    public class PersistentEnum<T extends Enum<T>> extends EnumType<T>
    {
        @Override
        public  void
                nullSafeSet(PreparedStatement preparedStatement, T obj, int index, SharedSessionContractImplementor session)    throws HibernateException,
                                                                                                                                SQLException
        {
            if(obj == null)
            {
                preparedStatement.setNull(index, java.sql.Types.OTHER);
            }
            else
            {
                preparedStatement.setObject(index, obj.toString(), java.sql.Types.OTHER);
            }
    
        }
    }
    

    With this, the former posted hbm.xml code is working.