![](/img/trans.png)
[英]Use postgres table sequence instead of sharing hibernate_sequence
[英]Slick use Postgres Sequence instead of serial
我的postgres中有一個現有的架構,我想使用Slick,如何強制執行此id列以在Slick中使用postgres序列?
class User(id: Int, first: String, last: String)
class Users(tag: Tag) extends Table[Int](tag, "users") {
def id = column[Int]("id", O PrimaryKey)
def * = id
}
val users = TableQuery[Users]
val usersSequence = Sequence[Int]("users_seq") start 1 inc 1
這是我現有的架構:
create table users (
id bigint not null,
...
)
create sequence users_seq;
如@a_horse_with_no_name所述, 串行列正在使用序列 。 在Slick
您只需要使用AutoInc
定義列,在您的情況下:
def id = column[Int]("id", O.AutoInc, O.PrimaryKey)
在定義Serial
列時,在PostgreSQL
端,您只需返回一個帶有Default Value: nextval('user_id_seq'::regclass)
的Int
列Default Value: nextval('user_id_seq'::regclass)
,這是用於遞增值的序列。
無需在架構代碼中手動創建序列:
class User(id: Int, first: String, last: String)
class Users(tag: Tag) extends Table[Int](tag, "users") {
def id = column[Int]("id", O.AutoInc, O.PrimaryKey)
def * = id
}
val users = TableQuery[Users]
評論后編輯:
我運行了你的sql語句,為序列添加了表alter:
create table users (
id bigint not null
);
create sequence users_seq;
alter table users alter column id set default nextval('users_seq');
在我的數據庫,現在我有一列的表id
類型的Int
的順序和默認值: nextval('users_seq'::regclass)
。 這與我之前寫過的相同,你有一個表格,其序列應用於id列,光滑的代碼也不會改變,你可以嘗試在本地數據庫上運行它。
需要注意的是你的SQL語句是錯誤的,你創建一個序列,但它沒有分配到任何列,你要么必須使用alter或直接與序列中添加一列如圖所示這里 。 希望這更清楚。
Ps我不完全確定的一件事是BigInt
Postgres字段被映射到Scala Long
,但可能與序列無關,但不確定,為了保持一致性,我總是將它們映射到Long
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.