This question has been asked and answered for slick 1 and 2, but the answers don't seem to be valid for slick 3.
Attempting to use the pattern in How to use Enums in Scala Slick?,
object MyEnumMapper {
val string_enum_mapping:Map[String,MyEnum] = Map(
"a" -> MyEnumA,
"b" -> MyEnumB,
"c" -> MyEnumC
)
val enum_string_mapping:Map[MyEnum,String] = string_enum_mapping.map(_.swap)
implicit val myEnumStringMapper = MappedTypeMapper.base[MyEnum,String](
e => enum_string_mapping(e),
s => string_enum_mapping(s)
)
}
But MappedTypeMapper
has not been available since slick 1, and the suggested MappedColumnType
for slick 2 is no longer available, despite being documented here.
What's the latest best practice for this?
What exactly do you mean by MappedColumnType
is no longer available? It comes with the usual import of the driver. Mapping an enum to a string and vice versa using MappedColumnType
is pretty straight forward:
object MyEnum extends Enumeration {
type MyEnum = Value
val A = Value("a")
val B = Value("b")
val C = Value("c")
}
implicit val myEnumMapper = MappedColumnType.base[MyEnum, String](
e => e.toString,
s => MyEnum.withName(s)
)
A shorter answer so that you don't need to implement myEnumMapper
yourself:
import play.api.libs.json.{Reads, Writes}
object MyEnum extends Enumeration {
type MyEnum = Value
val A, B, C = Value // if you want to use a,b,c instead, feel free to do it
implicit val readsMyEnum = Reads.enumNameReads(MyEnum)
implicit val writesMyEnum = Writes.enumNameWrites
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With