postgresqlspring-boothibernatespring-data-jpa

Hiberate 6 and Spring Boot 3: Unable to map Java enum to PostgreSql enum


We're migrating our Java 17 service from Spring Boot 2 to Spring Boot 3 and thus Hibernate 5 to Hibernate 6. I anonymized the examples below by using an animal example.

Our table column is defined as:

CREATE TYPE animal as ENUM ('dog', 'cat', 'other');

In Java, the Spring Boot 2 the working implementation was:

public enum AnimalType{
  DOG("dog"),
  CAT("cat"),
  UNKNOWN("other");

  private String type;

  AnimalType(String type) {
    this.type = type;
  }

  @Override
  public String getType() {
     return type;
  }

  public static AnimalType fromType(final String type) {
    if ("dog".equals(type)) {
      return AnimalType.DOG;
    } else if ("cat".equals(type)) {
      return AnimalType.CAT;
    } else {
       return AnimalType.UNKNOWN;
    }
  }
}
@TypeDefs({
  @TypeDef(
    name = "animal_type",
    typeClass = AnimalTypeSql.class
  )
})

@Type(type = "animal_type")
@Column(name = "TYPE")
private AnimalType animalType;
public class AnimalTypeSql extends EnumType { // EnumType is now deprecated so we want to avoid using it

  @Override
  public Object nullSafeGet(final ResultSet rs, final String[] names, final SharedSessionContractImplementor session, final Object owner) throws SQLException {
    if (rs.wasNull() || names == null || names.length == 0) {
      return null;
    }
    final String value = rs.getString(names[0]);
    return AnimalType.fromType(value);
  }

  @Override
  public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws SQLException {
    if (value == null) {
      st.setNull(index, Types.OTHER);
    } else {
      st.setObject(index, value.toString, Types.OTHER);
  }
}

In Spring Boot 3.2.9 we've tried a number of combinations on the column

//@Convert(converter = AnimalTypeConverter.class)
//@JdbcType(value = PostgreSQLEnumJdbcType.class)
//@JdbcTypeCode(SqlType.NAMED_ENUM)
//@Enumerated(EnumType.String)
@Column(name = "TYPE")
private AnimalType animalType;

The only thing we got to work was changing the enum to be:

public enum AnimalType{
  dog("dog"),
  cat("cat"),
  other("other");
 ....

and we want to avoid this because the mapping of DOG to dog isn't clear in some cases so we want to keep the enum name the same throughout the code for readability purposes.

No matter what we try, we see exceptions thrown when trying to insert data in the DB.


Solution

  • We have implemented persistable enumerations as follows:

    Define an interface that all your persistable enumerations will implement:

    public interface PersistableEnum<T> {
      T getValue();
    }
    

    Then we defined an abstract persistable enumeration converter as follows:

    @Converter
    public abstract class AbstractEnumConverter<T extends Enum<T> & 
      PersistableEnum<E>, E> implements AttributeConverter<T, E> {
      private final Class<T> clazz;
    
      public AbstractEnumConverter(final Class<T> clazz) {
        this.clazz = clazz;
      }
    
      @Override
      public E convertToDatabaseColumn(final T attribute) {
        return attribute != null ? attribute.getValue() : null;
      }
    
      @Override
      public T convertToEntityAttribute(final E dbData) {
        if (dbData == null) {
          return null;
        }
    
        final T[] enums = clazz.getEnumConstants();
    
        for (final T e : enums) {
          if (e.getValue().equals(dbData)) {
            return e;
          }
        }
    
        throw new UnsupportedOperationException("Unknown enumeration " + 
          dbData.toString());
      }
    }
    

    An example of a persistable enumeration is as follows:

    public enum Unit implements PersistableEnum<String> {
      OUNCES("oz"),
      POUNDS("lb"),
      GRAMS("g");
    
      private final String value;
    
      private Unit(final String value) {
        this.value = value;
      }
    
      public String getValue() {
        return this.value;
      }
    
      public static Unit fromValue(final String value) {
        for (final Unit unit : Unit.class.getEnumConstants()) {
          if (unit.getValue().equals(value)) {
            return unit;
          }
        }
    
        throw new IllegalArgumentException("Unknown unit " + value);
      }
    
      @Converter(autoApply = true)
      public static class UnitConverter 
        extends AbstractEnumConverter<Unit, String> {
    
        public UnitConverter() {
          super(Unit.class);
        }
      }
    }
    

    You then define your enumeration as an entity attribute as you would any other attribute. Nothing more needs to be done.

    @Column(length = 10)
    private Unit unit;
    

    A lot of the boiler plate code needed for conversion is handled in the AbstractEnumConverter and doesn't need to be implemented for each distinct enumeration.