如何在scala slick 3中实现枚举?

时间:2015-07-30 00:06:35

标签: database scala enums slick

这个问题已被提出并回答了光滑的1和2,但答案似乎对光滑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因光滑1而无法使用MappedColumnType,而且光滑2的建议app.refreshTapped = function() { console.log('tapped'); } 已不再可用,尽管已记录here

最新的最佳做法是什么?

2 个答案:

答案 0 :(得分:12)

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)
)

答案 1 :(得分:1)

一个简短的答案,这样您就无需自己实现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
}