Scala 如何在Slick中显式指定AutoInc列的值

Scala 如何在Slick中显式指定AutoInc列的值,scala,slick,slick-3.0,Scala,Slick,Slick 3.0,默认情况下,Slick忽略带有O.AutoInc标志的列中的值,并允许数据库在插入操作期间填充该值 但有时我需要为自动递增列插入一些特定的值,而Slick仍然会忽略它。有办法吗 我知道,我可以创建第二个表定义,而无需使用O.AutoInc标志,但我正在寻找更优雅的方法 更新: 以下是我的案例类和表定义: case class Transaction (id: Long, timestamp: LocalDateTime, comment: Option[String]) class Transa

默认情况下,Slick忽略带有
O.AutoInc
标志的列中的值,并允许数据库在插入操作期间填充该值

但有时我需要为自动递增列插入一些特定的值,而Slick仍然会忽略它。有办法吗

我知道,我可以创建第二个表定义,而无需使用
O.AutoInc
标志,但我正在寻找更优雅的方法

更新: 以下是我的案例类和表定义:

case class Transaction (id: Long, timestamp: LocalDateTime, comment: Option[String])
class Transactions(tag: Tag) extends Table[Transaction](tag, "tx") {
  implicit val localDTtoDate = MappedColumnType.base[LocalDateTime, Timestamp] (
    l => Timestamp.valueOf(l),
    d => d.toLocalDateTime
  )

  def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
  def timestamp = column[LocalDateTime]("ts")
  def comment = column[Option[String]]("comment")
  def * = (id, timestamp, comment) <> ((Transaction.apply _).tupled, Transaction.unapply)
}
case类事务(id:Long,timestamp:LocalDateTime,comment:Option[String])
类事务(tag:tag)扩展表[Transaction](tag,“tx”){
隐式val localDTtoDate=MappedColumnType.base[LocalDateTime,Timestamp](
l=>Timestamp.valueOf(l),
d=>d.toLocalDateTime
)
def id=列[Long](“id”,O.PrimaryKey,O.AutoInc)
def timestamp=列[LocalDateTime](“ts”)
def comment=列[选项[字符串]](“注释”)
def*=(id、时间戳、注释)((Transaction.apply 41;).tuple、Transaction.unapply)
}

如果您将
id
字段标记为
选项
al,您应该能够通过稍微调整
*
投影插入:

case类事务(id:Option[Long],时间戳:LocalDateTime,
注释:选项[字符串])
类事务(tag:tag)扩展表[Transaction](tag,“tx”){
//使用id列上的?方法将其映射到选项。
def*=(id.?,时间戳,注释)(
(Transaction.apply 41;.tuple,Transaction.unapply)
}
这样,使用
id=None
插入的行将生成一个新的
id
,而使用
id=Some(value)
插入的行将设置
id=value
。要读回插入的id,请使用返回。。。进入:

// `tx` is a Transaction instance, `transactions` is a
// TableQuery[Transactions] instance.
(transactions.returning(transactions.map(_.id)).into { (_, id) =>
  tx.copy(id = id)
}) += tx

我在与一个非常类似的问题作斗争时发现了这个问题。 遗憾的是,我们也无法使建议的解决方案发挥作用

我们决定让
O.AutoInc
离开,但保留序列和列的默认值为该序列的
nextval

  Column  |  Type  |                 Modifiers
----------+--------+----------------------------------------------
 id       | bigint | not null default nextval('id_seq'::regclass)
然后,当需要自动生成id时,我们只是在插入过程中省略了id

链接到文档的相关部分:

在这种情况下,它看起来像这样:

if (you have an explicit id) transactions += tx
else transactions.map(t => (t.timestamp, t.comment)) += (tx.timestamp, tx.comment)

如果
*
-投影使用ID列,则可以执行此操作。你能复制粘贴你的表格定义吗?@jkinkead当然!不幸的是,在这两种情况下,使用id:Option[Long]值仍然是自动生成的,使用一些(value)和非如何插入行?你在使用什么数据库?这应该适用于Slick 3.{0,1}和PostgreSQL。插入代码是理解的一部分,相关部分是:返回事务的事务。map(+u.id)+=tx数据库是PostgreSQLAh。您的问题实际上就在代码中。我将用一个例子更新我的答案。@akashi您需要执行。forceInsert而不是
+=