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.

1

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.

4

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật