如何在光滑中保留枚举值 [英] How to persist enum value in slick

查看:49
本文介绍了如何在光滑中保留枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下枚举:

object LoginStatus extends Enumeration() with BitmaskedEnumeration {
  type LoginStatus = Value
  val Active = Value("A")
  val Inactive = Value("I")
}

我需要持久化枚举A"的值,但是生成sql时结果为0.这是表映射:

I need to persist the value of the enum "A", but when the sql is generated the result is 0. this is the table mapping:

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 类,因为这样您就不必为最终使用的每个枚举创建映射器:

I would personally suggest making your own class inherit from Scala's Enumeration class because then you don't have to create mappers for every single enum you end up using:

这是我目前使用的流畅的 2.0 代码:

Here is the slick 2.0 code that I am currently using:

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(我还没有测试过):

This should also work in slick 1.0 ( I have not tested it ):

abstract class DBEnum extends Enumeration {
  implicit val enumMapper = MappedTypeMapper.base[Value, Int](_.id, this.apply)
}

现在你需要的枚举只是从 DBEnum 继承,它应该减少很多样板.

Now all you need for your enums is just to inherit from DBEnum and it should cut down on a lot of boiler plate.

如果您想使用字符串值而不是 Int,请相应地编辑代码.

Edit the code accordingly if you want to use string values instead of Ints.

这篇关于如何在光滑中保留枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆