Meaning of @GeneratedValue with strategy of TABLE

心已入冬 提交于 2019-12-02 04:49:32

问题


The JPA specification gives the following explanation of the annotation @GeneratedValue(strategy=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.

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 TABLE strategy using a table named SEQUENCE, with SEQ_NAME and SEQ_COUNT columns



来源:https://stackoverflow.com/questions/12121840/meaning-of-generatedvalue-with-strategy-of-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!