2017-02-16 16 views
2

默認情況下,Slick忽略O.AutoInc標誌的列中的值,並允許數據庫在插入操作期間填充該值。如何明確指定Slick中的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) 
} 
+0

如果你能做到這一點你的''-projection使用的ID柱。你能複製粘貼你的表格定義嗎? – jkinkead

+0

@jkinkead當然! – akashihi

回答

0

如果您標記您的id場爲Option人,你應該能夠有輕微的調整,以插入到你的*投影:

case class Transaction (id: Option[Long], timestamp: LocalDateTime, 
    comment: Option[String]) 
class Transactions(tag: Tag) extends Table[Transaction](tag, "tx") { 
    // Use the ? method on your id column to map it to an option. 
    def * = (id.?, timestamp, comment) <> (
    (Transaction.apply _).tupled, Transaction.unapply) 
} 

由此,您插入的行將生成id=None將生成新的id,而具有id=Some(value)的行將設置id=value。讀回插入的ID,使用returning ... into

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

不幸的是,使用id:Option [Long]值在兩種情況下仍然是自動生成的,使用Some(value)和None – akashihi

+0

如何插入行?你使用的是哪個數據庫?這應該適用於Slick 3. {0,1}和PostgreSQL。 – jkinkead

+0

插入代碼是理解的一部分,相關部分是:事務返回transactions.map(_。id)+ = tx數據庫是PostgreSQL – akashihi

0

我發現這個問題,同時具有非常類似的問題掙扎。 不幸的是,我們無法使建議的解決方案也能正常工作。

我們決定讓O.AutoInc去,但保留了序列和列的默認值是序列

Column | Type |     Modifiers 
----------+--------+---------------------------------------------- 
id  | bigint | not null default nextval('id_seq'::regclass) 

然後在插入過程中,我們只是省略了ID時,它需要的是的nextval自動生成。

鏈接到文檔的相關部分: http://slick.lightbend.com/doc/3.1.0/queries.html#inserting

在這個確切的情況下,它會是這個樣子:

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