如何在 scala slick 3 中实现枚举?
How to implement enums in scala slick 3?
已经针对 slick 1 和 2 提出并回答了此问题,但答案似乎对 slick 3 无效。
正在尝试使用 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)
)
}
但是 MappedTypeMapper
自 slick 1 以来就不再可用,尽管有记录 here。
,但 slick 2 的建议 MappedColumnType
不再可用
最新的最佳实践是什么?
MappedColumnType
不再可用是什么意思?它带有通常导入的驱动程序。使用 MappedColumnType
将枚举映射到字符串,反之亦然:
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)
)
一个更简短的答案,这样您就不需要自己实施 myEnumMapper
:
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
}
已经针对 slick 1 和 2 提出并回答了此问题,但答案似乎对 slick 3 无效。
正在尝试使用 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)
)
}
但是 MappedTypeMapper
自 slick 1 以来就不再可用,尽管有记录 here。
MappedColumnType
不再可用
最新的最佳实践是什么?
MappedColumnType
不再可用是什么意思?它带有通常导入的驱动程序。使用 MappedColumnType
将枚举映射到字符串,反之亦然:
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)
)
一个更简短的答案,这样您就不需要自己实施 myEnumMapper
:
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
}