I am using AttributeConvertor to convert an Enum to Short while persisting the value in database and vice-versa while reading the value from database as follows:
@Converter
class MyEnumConvertor : AttributeConverter<MyEnum, Short> {
override fun convertToDatabaseColumn(attribute: MyEnum): Short = MyEnum.toValue(attribute)
override fun convertToEntityAttribute(dbData: Short): MyEnum = MyEnum.fromValue(dbData)
}
enum class MyEnum(val value: Short) {
RED(0),
GREEN(1);
companion object {
private val valueToEnumMap = MyEnum.values().associateBy(MyEnum::value)
fun fromValue(value: Short): MyEnum = valueToEnumMap[value]
?: throw Exception("Invalid value: $value")
fun toValue(status: MyEnum): Short = status.value
}
}
Usage:
@Entity
@Table(name = "my_table")
class MyEntity(
@Id
val id: Long,
@Convert(converter = MyEnum::class)
@Column(name = "status", nullable = false)
val color: MyEnum
Now in other tables too I have many conversions like this, and it's around 10 convertors written now. I think it's not a good practice of having these many Convertors.
Any Solution on how to avoid these? Or, any genric solution where I can create only one convertor and reuse them?
PS: I know @Enumerated(Enumtype.ORDINAL) works, but if the order of enums is changed (say, RED and GREEN order) then it will break the code. So, not using this approach.