Difference between @GeneratedValue and @GenericGenerator

后端 未结 3 999
不知归路
不知归路 2020-12-04 13:24

Sometimes I find them together, sometimes alone... other times they seem to do the same.

What\'s the difference?

Here are three examples. What do they do of

3条回答
  •  Happy的楠姐
    2020-12-04 13:40

    When using an ORM it is often necessary to generate a primary key value.

    The @GeneratedValue annotation denotes that a value for a column, which must be annotated with @Id is generated. The elements strategy and generator on the annotation describe how the generated value is obtained.

    There are four possible values for the strategy element on the @GeneratedValue annotation: IDENTITY, AUTO, TABLE and SEQUENCE. See more.

    So to answer Part 2 of your question, the code snippet is indicating that the value of userId will be obtained through a sequence in the database.

    The generator element of the @GeneratedValue annotation denotes the name of the primary key generator. In Part1 of your question, the code snippet indicates that a generator named increment will be used to obtain the primary key value. increment is then defined in the next annotation @GenericGenerator. @GenericGenerator is a hibernate annotation used to denote a custom generator, which can be a class or shortcut to a generator supplied by Hibernate. increment is a shortcut to a Hibernate generator that:

    generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. Do not use in a cluster.

    In the Third Part of your question, the code uses a hilo Hibernate generator that:

    uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database.

提交回复
热议问题