Scala,Slick:如何使用自动生成的数字和字节数组插入

Scala,Slick:如何使用自动生成的数字和字节数组插入,scala,slick,Scala,Slick,摘要 您需要进行两项主要修改: 您需要一个TableQuery[FingerprintsTable]调用insert(或+=或+=打开);及 要取回插入的ID,您需要使用Slick中的returning方法 工作示例 很难从你发布的代码中准确地说出你的想法。下一次首先简化您的示例会很有帮助 我假设你的模型是这样的: FingerprintsModel.fingerprints.map(fi => (fi.customerId, fi.template_one, fi.template_tw

摘要

您需要进行两项主要修改:

  • 您需要一个
    TableQuery[FingerprintsTable]
    调用
    insert
    (或
    +=
    +=
    打开);及
  • 要取回插入的ID,您需要使用Slick中的
    returning
    方法
  • 工作示例

    很难从你发布的代码中准确地说出你的想法。下一次首先简化您的示例会很有帮助

    我假设你的模型是这样的:

    FingerprintsModel.fingerprints.map(fi => (fi.customerId, fi.template_one, fi.template_two, fi.created))
                    .insert((id, fingerprint.template_one, fingerprint.template_two, new DateTime()))
    
    我遗漏了一个字节数组以及创建和更新的字段,因为它们似乎与问题无关。换句话说,我简化了

    指纹表似乎正常。我忽略了外键,因为这似乎不相关。哦,
    O.NotNull
    现在已经被弃用了(至少在Slick 3中是这样)。您可以不使用它们,因为您的列不是
    选项

    我们需要的是表查询,我将在
    FingerprintsModel
    中添加它:

      case class Fingerprint(
        id: Long,
        customerId: String,
        template_one: Array[Byte]
      )
    
    您可以使用
    指纹
    插入数据。但是您要求返回ID,因此您希望使用
    指纹ID

    将其全部放在一起(再次使用Slick 3):


    我需要插入返回我在slick 2.0中自动生成的id
      case class Fingerprint(
        id: Long,
        customerId: String,
        template_one: Array[Byte]
      )
    
      lazy val fingerprints = TableQuery[FingerprintsTable]
      lazy val fingerprintsWithID = fingerprints returning fingerprints.map(_.id)
    
    object FingerprintExample extends App {
    
      import FingerprintsModel._
    
      val testData = Seq(
        Fingerprint(0L, "Alice", Array(0x01, 0x02)),
        Fingerprint(0L, "Bob",   Array(0x03, 0x04))
      )
    
      // A program that will create the schema, and insert the data, returning the IDs
      val program = for {
        _   <- fingerprints.schema.create
        ids <- fingerprintsWithID ++= testData
      } yield ids
    
      // Run the program using an in-memory database
      val db = Database.forConfig("h2mem1")
      val future = db.run(program)
      val result = Await.result(future, 10 seconds)
      println(s"The result is: $result")
    }
    
       The result is: List(1, 2)