gpt4 book ai didi

scala - 在 PostgreSQL 和 Slick 中使用自动递增字段

转载 作者:行者123 更新时间:2023-12-02 02:57:46 26 4
gpt4 key购买 nike

如何使用带有 Slick 映射表的 AutoInc 键将记录插入到 PostgreSQL 中?如果我在案例类中使用 和 Option 作为 id 并将其设置为 None,那么 PostgreSQL 将在插入时提示该字段不能为空。这适用于 H2,但不适用于 PostgreSQL:

//import scala.slick.driver.H2Driver.simple._
//import scala.slick.driver.BasicProfile.SimpleQL.Table
import scala.slick.driver.PostgresDriver.simple._
import Database.threadLocalSession

object TestMappedTable extends App{

case class User(id: Option[Int], first: String, last: String)

object Users extends Table[User]("users") {
def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
def first = column[String]("first")
def last = column[String]("last")
def * = id.? ~ first ~ last <> (User, User.unapply _)
def ins1 = first ~ last returning id
val findByID = createFinderBy(_.id)
def autoInc = id.? ~ first ~ last <> (User, User.unapply _) returning id
}

// implicit val session = Database.forURL("jdbc:h2:mem:test1", driver = "org.h2.Driver").createSession()
implicit val session = Database.forURL("jdbc:postgresql:test:slicktest",
driver="org.postgresql.Driver",
user="postgres",
password="xxx")

session.withTransaction{
Users.ddl.create

// insert data
print(Users.insert(User(None, "Jack", "Green" )))
print(Users.insert(User(None, "Joe", "Blue" )))
print(Users.insert(User(None, "John", "Purple" )))
val u = Users.insert(User(None, "Jim", "Yellow" ))
// println(u.id.get)
print(Users.autoInc.insert(User(None, "Johnathan", "Seagul" )))
}
session.withTransaction{
val queryUsers = for {
user <- Users
} yield (user.id, user.first)
println(queryUsers.list)

Users.where(_.id between(1, 2)).foreach(println)
println("ID 3 -> " + Users.findByID.first(3))
}
}

将上述内容与 H2 一起使用会成功,但如果我将其注释掉并更改为 PostgreSQL,则会得到:

[error] (run-main) org.postgresql.util.PSQLException: ERROR: null value in column "id" violates not-null constraint
org.postgresql.util.PSQLException: ERROR: null value in column "id" violates not-null constraint

最佳答案

这在这里工作:

object Application extends Table[(Long, String)]("application") {   
def idlApplication = column[Long]("idlapplication", O.PrimaryKey, O.AutoInc)
def appName = column[String]("appname")
def * = idlApplication ~ appName
def autoInc = appName returning idlApplication
}

var id = Application.autoInc.insert("App1")

这就是我的 SQL 的样子:

CREATE TABLE application
(idlapplication BIGSERIAL PRIMARY KEY,
appName VARCHAR(500));

更新:

与 User 映射表有关的具体问题(如问题中所示)可以按如下方式解决:

  def forInsert = first ~ last <>
({ (f, l) => User(None, f, l) }, { u:User => Some((u.first, u.last)) })

这来自test cases in the Slick git repository .

关于scala - 在 PostgreSQL 和 Slick 中使用自动递增字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13199198/

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