【问题标题】:Scala Slick How to insert rows with a previously returned autoincremental IDScala Slick如何插入具有先前返回的自动增量ID的行
【发布时间】:2016-04-06 17:22:45
【问题描述】:

事情就是这样。

我使用的是 Slick 3.1.0,基本上我有两个模型,一个对另一个有 FK 约束。比方说:

case class FooRecord(id: Option[Int], name: String, oneValue: Int)

class FooTable(tag: Tag) extends Table[FooRecord](tag, "FOO"){
  def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
  def name = column[String]("NAME")
  def oneValue = column[Int]("ONEVALUE")
}
val fooTable =  TableQuery[FooTable]

case class BarRecord(id: Option[Int], name: String, foo_id: Int)

class BarTable(tag: Tag) extends Table[BarRecord](tag, "BAR"){
  def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
  def name = column[String]("NAME")
  def fooId = column[Int]("FOO_ID")
  def foo = foreignKey("foo_fk", fooId, fooTable)(_.id)
}

这些用于存储一个 Foo 和几个 Bars,其中一个 Bar 只有一个 Foo。 我一直试图弄清楚如何在单个事务上执行完整的插入语句集。即。

DBIO.seq( 
 (fooTable returning fooTable.map(_id)) += Foo(None, "MyName", 42),
 (barTable returning batTable.map(_id)) += Bar(None, "MyBarname", FOO_KEY)
)

但问题是我找不到将 Foo ID 用作 Bar 实例字段上的 FOO_KEY 的方法。 当然,我可以执行两次 DBAction,但在我看来这非常糟糕。 有什么想法吗?

提前致谢

【问题讨论】:

    标签: scala orm slick


    【解决方案1】:

    最简单的方法就是对 DBIO 事务进行排序并将第一个事务的结果传递给第二个事务:

    val insertDBIO = for {
      fooId <- (fooTable returning fooTable.map(_id)) += Foo(None, "MyName", 42)
      barId <- (barTable returning batTable.map(_id)) += Bar(None, "MyBarname", fooId)
    } yield (fooId, barId)
    
    db.run(insertDBIO.transactionally)
    

    transactionally 调用将确保两者都在同一个连接上运行。

    【讨论】:

    • 最后我使用了一个非常相似的方法,但不知道事务性。惊人的。工作顺利!
    猜你喜欢
    • 2016-07-27
    • 1970-01-01
    • 2018-02-17
    • 1970-01-01
    • 2014-08-03
    • 2012-09-11
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    相关资源
    最近更新 更多