【问题标题】:Inserting pirmary key for Table with auto-increment使用自动增量插入表的主键
【发布时间】:2017-09-07 05:52:54
【问题描述】:

我正在尝试找到一种方法来在一个光滑的Table 上执行插入,其主键是自动增量但强制主键为映射案例类中的值。 IE。给定:

case class Foo(id: Int, name: String)

class FooTable(tag: Tag) extends Table[Foo](tag, "foo") {
  def id = column[Int]("id", O.PrimaryKey, O.AutoInc)

  def name = column[String]("name")

  def * = (id, name) <> (Foo.tupled, Foo.unapply)
}

val foos = TableQuery[FooTable]

如果我通过以下方式进行常规插入

db.run(foos += Foo(123,"bar"))

它会将id 设置为下一个自动增量 值,而不是将其设置为123。是否有语法强制将id 设置为提供案例类Foo?

【问题讨论】:

  • 如果出现 id 冲突,您希望发生什么?
  • @mfirry 此代码用于在测试期间加载初始数据。出于您指定的原因,我没有计划在生产代码中使用此功能

标签: scala slick


【解决方案1】:

结帐forceInsert

一开始插入可能会有点令人惊讶 [...] auto-incremented 会被自动忽略,因此插入它们有 没有效果。使用 forceInsert 允许实际插入 自动递增的列。

来源:Coming from SQL to Slick

【讨论】:

    猜你喜欢
    • 2013-11-12
    • 2012-02-22
    • 2015-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多