注解是如何工作的

注解是如何工作的

本文介绍了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.

Q1.这个序列生成器是利用数据库不断增加的数值生成能力还是自己生成数字?

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

Q2.如果 JPA 使用数据库自​​动增量功能,那么它是否适用于没有自动增量功能的数据存储?

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

Q3. 如果 JPA 自己生成数值,那么 JPA 实现如何知道接下来生成哪个值?它是否先咨询数据库以查看最后存储了什么值以生成值(last + 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)?

Q4.还请说明 @SequenceGenerator 注释的 sequenceNameallocationSize 属性.>

Q4. Please also shed some light on sequenceName and allocationSize properties of @SequenceGenerator annotation.

推荐答案

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 注解是如何工作的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 18:14