问题
The JPA specification gives the following explanation of the annotation @GeneratedValue(strategy=TABLE):
The
TABLEgenerator type value indicates that the persistence provider must assign primary keys for the entity using an underlying database table to ensure uniqueness.
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?
回答1:
Check out JavaDoc for TableGenerator, it has a nice example of how it works:
Example 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;
...
}
Example 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;
...
}
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 = ...
and incremenets the GEN_VALUE column. This mechanism can be used to emulate sequences or to take even further control of generated ids.
回答2:
In the case of EclipseLink, it uses an auxiliary table. The documentation says
By default, EclipseLink chooses the
TABLEstrategy using a table namedSEQUENCE, withSEQ_NAMEandSEQ_COUNTcolumns
来源:https://stackoverflow.com/questions/12121840/meaning-of-generatedvalue-with-strategy-of-table