简体   繁体   English

了解JPA序列发生器

[英]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开始,默认allocationSize50 ,定义序列如下

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM