Hibernate: rundown on how @GeneratedValue works

hibernate

Solution

I am assuming you are refering to the JPA @GeneratedValue.

The `@GeneratedValue` annotation tells the ORM how to figure out the value of that field.

For example:

 @Id
 @GeneratedValue(strategy=SEQUENCE, generator="CUST_SEQ")
 @Column(name="CUST_ID")
 public Long getId() { return id; }

 Example 2:

 @Id
 @GeneratedValue(strategy=TABLE, generator="CUST_GEN")
 @Column(name="CUST_ID")
 Long id;

The key thing to understand is that a generated value has a strategy and the strategy of the generated value determines what happens. In the above example the SEQUENCE generation strategy means that the ORM will ask the database for a new value for the sequence when saving an object for the first time. The second example specify a table generation strategy which means that the ORM will consult a row in a table to determine the value of a id. In example example 2 the details of which table is used are not show since it reference a generator called "CUST_GEN"

Typcial generators you will run into.

- Identity - After an insert ask the auto incerement column for the value of the item

- Sequence - the value comes from a db sequence

- table - the value comes from another table in the database

- auto - pick one of the above based on the database type

- UUID - generate a UUID before doing an insert

It is possible to develop custom generator. The interaction with the database will depend on generation strategy.

Problem

I am having trouble finding an accurate explanation of `@GeneratedValue` and the different strategies regarding on what happens from a database point of view. Will the database always be queried and the last value available returned? What happens if 2 different processes (different Hibernate apps) access the same table at the same time? Specifically with auto numeric values and sequences.

Original source