我有以下枚举:
object LoginStatus extends Enumeration() with BitmaskedEnumeration {
type LoginStatus = Value
val Active = Value("A")
val Inactive = Value("I")
}
我需要保留枚举“A”的值,但生成sql时结果为0。 这是表映射:
object LoginTable extends Table[Login]("login") {
def idLogin = column[Int]("idlogin", O.PrimaryKey, O.AutoInc)
def cdLogin = column[String]("cdlogin", O.NotNull)
def cdPass = column[String]("cdPass", O.NotNull)
def stLogin = column[LoginStatus]("stlogin", O.NotNull, O.DBType("character(1)"))
}
如何保存枚举值?
我实现了
implicit val charMapper = MappedTypeMapper.base[Char, String](
b => b.toString(),
i => i.charAt(0))
implicit def enum2StringMapper(enum: Enumeration) = MappedTypeMapper.base[enum.Value, Char](
b => b.toString.charAt(0),
i => enum.withName(i.toString))
implicit val LoginStatusMapper = enum2StringMapper(LoginStatus)
但结果是:
[error] c.Login - Invalid value for type int : A
最佳答案
我个人建议让您自己的类继承 Scala 的 Enumeration 类,因为这样您就不必为最终使用的每个枚举创建映射器:
这是我当前使用的 slick 2.0 代码:
abstract class DBEnum extends Enumeration {
import slick.jdbc.MappedJdbcType
import slick.driver.JdbcDriver.simple._
implicit val enumMapper = MappedJdbcType.base[Value, Int](_.id, this.apply)
}
这应该也适用于 slick 1.0(我还没有测试过):
abstract class DBEnum extends Enumeration {
implicit val enumMapper = MappedTypeMapper.base[Value, Int](_.id, this.apply)
}
现在,您的枚举所需的只是从 DBEnum 继承,它应该减少大量的样板。
如果您想使用字符串值而不是整数,请相应地编辑代码。
关于scala - 如何在光滑中保留枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19273805/