gpt4 book ai didi

scala - Slick:autoInc 在 MultiDBCakeExample 示例中是如何工作的?

转载 作者:行者123 更新时间:2023-12-05 00:32:16 25 4
gpt4 key购买 nike

我试图了解 Slick 是如何工作的以及如何使用它......并查看他们在 GitHub 中的示例我最终在 MultiDBCakeExample.scala 中得到了这个代码片段| :

trait PictureComponent { this: Profile => //requires a Profile to be mixed in...
import profile.simple._ //...to be able import profile.simple._

object Pictures extends Table[(String, Option[Int])]("PICTURES") {
...

def * = url ~ id

val autoInc = url returning id into { case (url, id) => Picture(url, id) }

def insert(picture: Picture)(implicit session: Session): Picture = {
autoInc.insert(picture.url)
}
}
}

我想 *方法返回表中的一行,而 autoInc应该以某种方式提供自动增加实体 id 的功能......但说实话,我在理解这段代码时遇到了一些麻烦。什么 returning引用?什么 autoInc返回?

我查看了 Slick 文档,但找不到有用的信息。任何帮助将非常感激 ;-)

最佳答案

因为那 autoInc可能会令人困惑,我将为您提供一个工作示例(请注意,我的数据库是 PostgreSQL,因此我需要使用 forInsert 进行破解,以便使 Postgresql 驱动程序增加 auto-inc 值)。

case class GeoLocation(id: Option[Int], latitude: Double, longitude: Double, altitude: Double)

/**
* Define table "geo_location".
*/
object GeoLocations extends RichTable[GeoLocation]("geo_location") {
def latitude = column[Double]("latitude")
def longitude = column[Double]("longitude")
def altitude = column[Double]("altitude")

def * = id.? ~ latitude ~ longitude ~ altitude <> (GeoLocation, GeoLocation.unapply _)
def forInsert = latitude ~ longitude ~ altitude <> ({ (lat, long, alt) => GeoLocation(None, lat, long, alt) },
{ g: GeoLocation => Some((g.latitude, g.longitude, g.altitude)) })
}

我的 RichTable 是一个抽象类,以便不为我拥有的每个表声明 id,而是扩展它:
abstract class RichTable[T](name: String) extends Table[T](name) {
def id = column[Int]("id", O.PrimaryKey, O.AutoInc)

val byId = createFinderBy(_.id)

}

并使用它:
GeoLocations.forInsert.insert(GeoLocation(None, 22.23, 25.36, 22.22))

既然你通过了 Noneid ,当 Slick 插入这个新实体时,它会由 PostgreSql 驱动程序自动生成。
自从我开始使用 Slick 以来,我已经有几个星期了,我真的很推荐它!

更新 : 如果不想用 forInsert预测,另一种方法如下 - 在我的情况下,实体是 Address .

在模式创建时为每个表创建序列:
session.withTransaction {
DBSchema.tables.drop
DBSchema.tables.create
// Create schemas to generate ids too.
Q.updateNA("create sequence address_seq")
}

定义一个使用序列生成 id 的方法(我在 once 类中定义了这个 RichTable:
  def getNextId(seqName: String) = Database { implicit db: Session =>
Some((Q[Int] + "select nextval('" + seqName + "_seq') ").first)
}

并在映射器覆盖 insert 中方法如:
  def insert(model : Address) = Database { implicit db: Session =>
*.insert(model.copy(id = getNextId(classOf[Address].getSimpleName())))
}

现在,您可以通过 None当你做一个插入时,这个方法会为你做一个很好的工作......

关于scala - Slick:autoInc 在 MultiDBCakeExample 示例中是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13739182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com