【问题标题】:How to INSERT into Postgres table with autogenerated id如何使用自动生成的 id 插入 Postgres 表
【发布时间】:2018-11-14 16:32:37
【问题描述】:

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

我有一个表格,例如 3 个列(id、col1、col2), 和 2 行(492d0a75、some_text1、some_text2)。

我的表的列 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。

我该怎么做?

【问题讨论】:

  • insert into mytable(col1, col2) select col1, 'other_value' from mytable
  • @Andreas“我的表的列 ID 没有自动递增”这个插入不正确我会得到“错误:“id”列中的空值违反了 NOT NULL 约束”
  • MyEntity original = em.find(MyEntity.class, id); em.persist(new MyEntity(original.getCol1(), "other value");
  • @JBNizet 我正在尝试通过 flyway 迁移脚本来做到这一点
  • 然后用 Java 编写迁移以生成 UUID,或在迁移脚本中硬编码预先计算的 UUID。

标签: java sql postgresql hibernate insert


【解决方案1】:

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

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

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

之后我可以使用来自postgres docs的uuid_generate_v4()

我的最终查询如下所示:

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

【讨论】:

    猜你喜欢
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 2017-10-10
    • 2016-10-22
    • 1970-01-01
    • 2021-06-09
    • 2011-04-03
    相关资源
    最近更新 更多