问题描述
我已将 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)公共 int getId() {返回 this.id;}
我在这个配置中看到的是,hibernate 已经在持久化时分配了 id 值 > 3000,而对使用序列的查询显示如下:
database=# select last_value from entity_id_seq;最后一个值------------69
(1 行)
问题:
有什么不对吗?
休眠是否应该与序列表同步?
如果没有,它在哪里存储最后生成的 id?
谢谢.
我遇到了同样的问题.这与Hibernate的id分配策略有关.当您选择 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)公共 int getId() {返回 this.id;}
不过,我也听说过将 HiLo 策略与 allocationSize=1 结合使用并不是一个好的做法.当您必须处理数据库管理的序列时,有些人建议使用 GenerationType.AUTO 代替
更新:我最终使用了 allocationSize=1,现在一切似乎都如我所愿.我的应用程序是这样的,反正我真的不需要 ID 块,所以 YMMV.>
I've configured Hibernate to use PostgreSQL sequence (via annotations) to generate values for primary key id column as follows:
@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 row)
Questions:
Is there anything wrong or not?
Should hibernate sync with the sequence table?
If not, where does it store the last generated id?
Thank you.
I had the same problem. It is related to the id allocating strategies of Hibernate. Whe n you choose GenerationType.SEQUENCE, Hibernate uses HiLo strategy which allocates IDs in blocks of 50 by default. So you can explicitly set allocationSize value like this:
@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;
}
Though, I've also heard opinions that using HiLo strategy with allocationSize=1 is not a good practice. Some people recommend to use GenerationType.AUTO instead when you have to deal with database-managed sequences
Update: I did end up going with allocationSize=1, and things seem to work as I expect now. My application is such that I don't really need blocks of IDs anyway, so YMMV.
这篇关于Hibernate使用PostgreSQL序列不影响序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!