使用枚举更新 table

Updating table with enum

正在尝试将信息插入数据库,如下所示:

(UUID, EnumType)

具有以下逻辑:

var t = TestTable.query.map(t=> (t.id, t.enumType)) ++= toAdd.map(idTest, enumTest)))

但编译器为 TestTable.query.map(t=> (t.id, t.enumType)) 抛出错误,它将其解释为 Iteratable[Nothing] 类型,我是不是遗漏了什么?


测试 table 看起来像这样:

object TestTable {
  val query = TableQuery[TestTable]
}

class TestTable(tag: slick.lifted.Tag) extends Table[TestTable](tag, "test_table") {
  val id = column[UUID]("id")
  val enumType = column[EnumType]("enumType")

  override val * = (id, testType) <> (
    (TestTable.apply _).tupled,
    TestTable.unapply
  )

假设您有以下数据结构:

object Color extends Enumeration {
  val Blue = Value("Blue")
  val Red = Value("Red")
  val Green = Value("Green")
}

case class MyType(id: UUID, color: Color.Value)

定义 slick schema 如下:

class TestTable(tag: slick.lifted.Tag) extends Table[MyType](tag, "test_table") {
  val id = column[UUID]("id")
  val color = column[Color.Value]("color")

  override val * = (id, color) <> ((MyType.apply _).tupled, MyType.unapply)
}

object TestTable {
  lazy val query = TableQuery[TestTable]
}

要将枚举映射到 SQL 数据类型 slick 需要隐式 MappedColumnType:

implicit val colorTypeColumnMapper: JdbcType[Color.Value] = MappedColumnType.base[Color.Value, String](
  e => e.toString,
  s => Color.withName(s)
)

现在您可以通过以下方式将值插入数据库:

val singleInsertAction = TestTable.query += MyType(UUID.randomUUID(), Color.Blue)

val batchInsertAction = TestTable.query ++= Seq(
  MyType(UUID.randomUUID(), Color.Blue),
  MyType(UUID.randomUUID(), Color.Red),
  MyType(UUID.randomUUID(), Color.Green)
)