JPA AttributeConverter not working with enum in the json column field

2k Views Asked by At

I have a table like this

CREATE TABLE `test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `json_col` json NOT NULL,
  PRIMARY KEY (`id`)
)

My data model looks like this

@Entity
@TypeDef(name = "json", typeClass = JsonStringType.class)
public class ServiceVersion extends EntityAuditing {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private int id;

  @NotNull
  @Type(type = "json")
  @Column(columnDefinition = "json")
  private JsonColumn jsonCol;
}
@AllArgsConstructor
@Getter
public enum TestEnum {
  ABC("abc.com"),
  DEF("def.com");

  private String value;
}
public class JsonColumn {
  private TestEnum enumVal;
}

To convert the enum TestEnum, I use the below AttributeConverter

@Converter(autoApply = true)
public class EnumConverter implements AttributeConverter<TestEnum, String> {

  @Override
  public String convertToDatabaseColumn(TestEnum value) {
    if (value == null) {
      return null;
    }
    return value.getValue();
  }

  @Override
  public TestEnum convertToEntityAttribute(String value) {
    if (value == null) {
      return null;
    }

    return Stream.of(TestEnum.values())
        .filter(v -> v.getValue().equals(value))
        .findFirst()
        .orElseThrow(IllegalArgumentException::new);
  }
}

But it looks like AttributeConverter class is not invoked if the enum is not defined as column in the entity class. In my case, I use hibernate-types to store the json. How can I store the enum with its value and instead of name?

With the above code, the column json_col is stored in DB, with enum name like this

{
  "enumVal": "ABC"
}

However, I want to store with the enum value like this.

{
  "enumVal": "abc.com"
}
1

There are 1 best solutions below

0
On

As it is stated in the documentation:

If the autoApply element is specified as true, the persistence provider must automatically apply the converter to all mapped attributes of the specified target type for all entities in the persistence unit except for attributes for which conversion is overridden by means of the Convert annotation (or XML equivalent).

The target type of your attribute is JsonColumn so the converter is not applied. The converter will be automatically applied to the following field for example:

@Column
private TestEnum testColumn;