Last active
September 15, 2024 01:17
-
-
Save tlux/f10122232f1683c3f8223ddcd5ba4088 to your computer and use it in GitHub Desktop.
Hibernate Attibute Converter for Enums
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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