【问题标题】:Hibernate and postgresql bigserial - nonsequentialHibernate 和 postgresql bigserial - 非顺序
【发布时间】:2017-04-30 00:58:24
【问题描述】:

我正在使用 postgres 和 Hibernate,我注意到我生成的 id 有一些奇怪的地方。它在序列中产生了巨大的跳跃,我有一个 1524 行的表,但最高 id 仍然是 602778。

我的 id 列是这样定义的:

id bigserial

并得到nextval('my_id_seq'::regclass)的支持

my_id_seq 的起始值为 1,增量为 1,并且在通过 SQuirreL 对其调用 nextval 时会很好地递增。

在我的 Hibernate 实体中,id 映射如下:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

什么会导致 id 序列突然跳跃(有时它从 4152 跳跃到 12041)?

【问题讨论】:

  • SERIAL PostgreSQL 中的类型和序列已知包含间隙(因为它们的生成高于任何事务——因此生成的值永远不会回滚)。但从统计上看,回滚事务不会导致如此巨大的跳跃(只有当您的应用程序有一些严重的错误,它试图生成许多实体但失败了——但我认为这极不可能)
  • 这是在测试环境中,有一个定期运行的进程。有足够多的失败项目和一些时间它可能会解释它。检查生产,那里还不错,9716 行,最大 id 是 43083。无论如何,我刚刚修复了导致尝试失败的问题,作为另一项任务的一部分,希望不会再有差距。

标签: java postgresql hibernate


【解决方案1】:

回滚和错误会这样做。 例如:

t=# create table s(i serial);
CREATE TABLE
t=# insert into s values (DEFAULT);
INSERT 0 1
t=# insert into s values (DEFAULT) returning i;;
 i
---
 2
(1 row)

INSERT 0 1

现在开始交易:

t=# begin;
BEGIN
t=# insert into s values (DEFAULT) returning i;
 i
---
 3
(1 row)

INSERT 0 1
t=# rollback;
ROLLBACK

使用的值 3,现在有差距:

t=# insert into s values (DEFAULT) returning i;
 i
---
 4
(1 row)

INSERT 0 1

检查:

t=# select * from s;
 i
---
 1
 2
 4
(3 rows)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    相关资源
    最近更新 更多