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"
}
As it is stated in the documentation:
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: