JPA @SequenceGenerator批注如何工作 [英] How does the JPA @SequenceGenerator annotation work

查看:114
本文介绍了JPA @SequenceGenerator批注如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习JPA,并且对@SequenceGenerator注释感到困惑.

I am learning JPA and have confusion in the @SequenceGenerator annotation.

据我了解,它会自动为实体的数字标识字段/属性分配一个值.

To my understanding, it automatically assigns a value to the numeric identity fields/properties of an entity.

问题1.此序列生成器是利用数据库不断增长的数值生成功能还是自行生成数字?

Q1. Does this sequence generator make use of the database's increasing numeric value generating capability or generates the number on its own?

第二季度.如果JPA使用数据库自​​动增量功能,那么它可以用于没有自动增量功能的数据存储吗?

Q2. If JPA uses a database auto-increment feature, then will it work with datastores that don't have an auto-increment feature?

问题3.如果JPA自己生成数字值,那么JPA实现如何知道接下来要生成哪个值?它是否先咨询数据库以查看最后存储了什么值才能生成该值(最后+ 1)?

Q3. If JPA generates numeric value on his own, then how does the JPA implementation know which value to generate next? Does it consult with the database first to see what value was stored last in order to generate the value (last + 1)?

推荐答案

sequenceName是数据库中序列的名称.这是您指定数据库中已经存在的序列的方式.如果走这条路线,则必须指定allocationSize,该值必须与数据库序列用作其自动增量"的值相同.

sequenceName is the name of the sequence in the DB. This is how you specify a sequence that already exists in the DB. If you go this route, you have to specify the allocationSize which needs to be the same value that the DB sequence uses as its "auto increment".

用法:

@GeneratedValue(generator="my_seq")
@SequenceGenerator(name="my_seq",sequenceName="MY_SEQ", allocationSize=1)

如果需要,可以让它为您创建一个序列.但是要这样做,您必须使用SchemaGeneration来创建它.为此,请使用:

If you want, you can let it create a sequence for you. But to do this, you must use SchemaGeneration to have it created. To do this, use:

@GeneratedValue(strategy=GenerationType.SEQUENCE)

此外,您可以使用自动生成,它将使用表格来生成ID.使用此功能时,还必须在某个时候使用SchemaGeneration,以便可以创建生成器表.为此,请使用:

Also, you can use the auto-generation, which will use a table to generate the IDs. You must also use SchemaGeneration at some point when using this feature, so the generator table can be created. To do this, use:

@GeneratedValue(strategy=GenerationType.AUTO)

这篇关于JPA @SequenceGenerator批注如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆