@GeneratedValue与TABLE策略的含义 [英] Meaning of @GeneratedValue with strategy of TABLE
问题描述
JPA规范对注释@GeneratedValue(strategy=TABLE)
提供了以下说明:
The JPA specification gives the following explanation of the annotation @GeneratedValue(strategy=TABLE)
:
TABLE
生成器类型值表示持久性提供程序必须使用基础数据库表为实体分配主键,以确保唯一性.
The
TABLE
generator type value indicates that the persistence provider must assign primary keys for the entity using an underlying database table to ensure uniqueness.
但是使用基础数据库表"在实际中是什么意思?这是否意味着使用辅助表?还是通过扫描实体表来查找未使用的ID?还是其他?
But what does "using an underlying database table" mean in practice? Does it mean using an auxiliary table? Or by scanning the entity-table to find an ID not in use? Or something else?
推荐答案
签出用于TableGenerator
的JavaDoc,它有一个很好的工作方式示例:
Check out JavaDoc for TableGenerator
, it has a nice example of how it works:
示例1:
@Entity public class Employee {
...
@TableGenerator(
name="empGen",
table="ID_GEN",
pkColumnName="GEN_KEY",
valueColumnName="GEN_VALUE",
pkColumnValue="EMP_ID",
allocationSize=1)
@Id
@GeneratedValue(strategy=TABLE, generator="empGen")
int id;
...
}
示例2:
@Entity public class Address {
...
@TableGenerator(
name="addressGen",
table="ID_GEN",
pkColumnName="GEN_KEY",
valueColumnName="GEN_VALUE",
pkColumnValue="ADDR_ID")
@Id
@GeneratedValue(strategy=TABLE, generator="addressGen")
int id;
...
}
基本上,ID_GEN
是键值对的内部(非业务)表.每次JPA想要生成ID时,它都会查询该数据库:
Basically ID_GEN
is an internal (non-business) table of key-value pairs. Every time JPA wants to generate ID it queries that database:
SELECT GEN_VALUE
FROM ID_GEN
WHERE GEN_KEY = ...
并增加GEN_VALUE
列.这种机制可用于模拟序列,甚至可以进一步控制生成的ID.
and incremenets the GEN_VALUE
column. This mechanism can be used to emulate sequences or to take even further control of generated ids.
这篇关于@GeneratedValue与TABLE策略的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!