[英]Understanding JPA sequence generator
I'm using spring data JPA's sequence generator to assign primary keys to entities.我正在使用 spring 数据 JPA 的序列生成器将主键分配给实体。
Model contains: Model 包含:
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_post")
@SequenceGenerator(name = "seq_post", allocationSize = 5)
private Long id;
The corresponding sequence definition(for SQL Server DB):对应的序列定义(SQL Server DB):
CREATE SEQUENCE dbo.seq_post START WITH 1 INCREMENT BY 5;
Since I wanted to start the ids from 100 instead of 1, so I updated the sql script to由于我想从 100 而不是 1 开始 id,所以我将 sql 脚本更新为
CREATE SEQUENCE dbo.seq_post START WITH 100 INCREMENT BY 5;
And then I encountered the problem as mentioned here .然后我遇到了这里提到的问题。 I fixed it by the solution mentioned there.
我通过那里提到的解决方案修复了它。
This made me wonder, when I want the DB sequence to start from 1 then why does this issue does not happen?这让我想知道,当我希望数据库序列从 1 开始时,为什么这个问题不会发生? Based on the answer mentioned here I would expect the ids to not start from 1, but that does not happen.
根据这里提到的答案,我希望 id 不是从 1 开始,但这不会发生。 Why is that the case?
为什么会这样?
Well first check if you set the property hibernate.id.new_generator_mappings
to true
as recomended首先检查您是否按照建议将属性
hibernate.id.new_generator_mappings
设置为true
Than you are right in adjusting the allocationSize
with the sequence INCREMENT BY
.比您使用序列
INCREMENT BY
调整allocationSize
是正确的。
If you want to start the ID
with a specific value it seems to obey the following rules:如果您想以特定值开始
ID
,它似乎遵循以下规则:
to start with one set the sequence to START WITH 1
(this seems to be an exception)从一个开始,将序列设置为
START WITH 1
(这似乎是一个例外)
to start with X > 1
set the sequence START WITH X + 50
(accually the same is true for X < 1
)从
X > 1
开始设置序列START WITH X + 50
(实际上X < 1
也是如此)
eg to start with 5000
with the default allocationSize
of 50
define the sequence as follows例如,从
5000
开始,默认allocationSize
为50
,定义序列如下
create sequence sub_seq
START WITH 5050
INCREMENT BY 50
NOCACHE;
Note that I'm using the NOCACHE
option, because I assume Hibernate is the only user of this sequence, so caching is not realy meningfull (and actually replaced with the allocation size.请注意,我使用的是
NOCACHE
选项,因为我假设 Hibernate 是这个序列的唯一用户,所以缓存并不是真正的完整(实际上是用分配大小替换。
You also loose between the sessions approx.你也在会话之间放松。 1/2 of the
allocationSize
of the ID
s and you do not want to increase it with additional loss of the cached ID
s. ID
s 的allocationSize
的 1/2 并且您不希望增加它并额外丢失缓存的ID
s。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.