我已将Hibernate配置为使用PostgreSQL序列(通过注释)为主键id列生成值,如下所示:

@Id 
@SequenceGenerator(name="pk_sequence",sequenceName="entity_id_seq")
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="pk_sequence")
@Column(name="id", unique=true, nullable=false)
public int getId() {
    return this.id;
}

What I see with this configuration is that hibernate is already assigning id values > 3000 on persisting, whereas the query on used sequence shows the following:

database=# select last_value from entity_id_seq;
last_value 
------------
     69

(1排)

Questions:
Is there anything wrong or not?
Should hibernate sync with the sequence table?
If not, where does it store the last generated id?

非常感谢.

推荐答案

我也有同样的问题.这与Hibernate的id分配策略有关.当您 Select GenerationType.SEQUENCE时,Hibernate使用HiLo策略,默认情况下以50个块的形式分配ID.所以你可以像这样显式地设置allocationSize值:

@Id 
@SequenceGenerator(name="pk_sequence",sequenceName="entity_id_seq", allocationSize=1)
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="pk_sequence")
@Column(name="id", unique=true, nullable=false)
public int getId() {
    return this.id;
}

不过,我也听到一些观点认为,将HiLo策略与allocationSize=1结合使用不是一个好做法.有些人建议在处理数据库管理的序列时使用GenerationType.AUTO

Update:我最终还是 Select 了allocationSize=1,现在一切都如我所期望的那样顺利.我的应用程序是这样的,反正我真的不需要ID块,所以YMMV.

Postgresql相关问答推荐

利用PostgreSQL查询中表的顺序来计算包含每次时间的时间范围

将XML解析从T-SQL迁移到Postgres时出现问题

当条件的计算结果为假(或真)时停止执行查询

单个WAL文件中的操作会影响哪些表和多少行

当参数大小超过 393166 个字符时,PSQL 准备语句查询挂起

AWS RDS Postgres 性能缓慢的数据传输

使用 select 在带有特殊字符的字符串中查找数据

是否可以在 postgresql 中添加表元数据?

在 Postgres 中查询 JSON 对象数组

当脚本工作时,Postgres now() 时间戳不会改变

在 postgres 中删除所有共享相同前缀的表

无法登录 PostgreSQL 数据库

?(问号)运算符在 Rails 中查询 Postgresql JSONB 类型

PostgreSQL:将时间戳转换为时间 - 或仅从时间戳列中检索时间

用于更改 postgresql 用户密码的 bash 脚本

manage.py 迁移时必须是关系 django_site 的所有者

向 Postgres 整数数组添加值

Python PostgreSQL 模块.哪个最好?

Postgres 中有多少表分区太多了?

学习 PL/pgSQL 的好资源?