Skip to content

Instantly share code, notes, and snippets.

@tlux
Last active September 15, 2024 01:17
Show Gist options
  • Save tlux/f10122232f1683c3f8223ddcd5ba4088 to your computer and use it in GitHub Desktop.
Save tlux/f10122232f1683c3f8223ddcd5ba4088 to your computer and use it in GitHub Desktop.
Hibernate Attibute Converter for Enums
abstract class EnumConverter<T : Enum<T>, V>(
private val entries: EnumEntries<T>,
private val dumpValue: (T) -> V
) : AttributeConverter<T, V> {
override fun convertToDatabaseColumn(enumValue: T?): V? {
return enumValue?.let { dumpValue(it) }
}
override fun convertToEntityAttribute(dbValue: V?): T? {
return dbValue?.let { value ->
entries.firstOrNull { dumpValue(it) == value }
?: throw IllegalArgumentException("Unknown enum value: $value")
}
}
}
// usage:
@Converter
class MyEnumConverter : EnumConverter<MyEnum, String>(MyEnum.entries, { it.id })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment