繁体   English   中英

如何使用自动生成的ID插入Postgres表

[英]How to INSERT into Postgres table with autogenerated id

我正在尝试通过一些更改将当前行的副本添加到表中。

我有带有3个列(id,col1,col2)和2行(492d0a75,some_text1,some_text2)的表。

我表的Colume ID不会自动递增,因此我使用:

@Id
@GeneratedValue(generator = "uuid_gen")
@GenericGenerator(name = "uuid_gen", strategy = "uuid2")
@Column(name = "id", length = 36)

休眠注释以生成unic id。

我想做这样的事情:

insert into mytable(id, col1, col2)
select id, col1, 'other_value'
from mytable;

但是不能这样做,因为id不会是unic。

我怎样才能做到这一点?

为此,我要安装“ uuid-ossp”

要安装uuid-ossp模块,请使用CREATE EXTENSION语句,如下所示:

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

之后,现在我可以使用Postgres 文档中的 uuid_generate_v4()

我的最终查询如下所示:

insert into mytable (id, col1, col2)
select uuid_generate_v4(), col1, 'other_value'
from mytable;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM