I am having troubling 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 process (different Hibernate apps) access to the same table at the same time?specifically with auto numeric values and sequences
The @GeneratedValue annotation tells the ORM how to figure out the value of that field. Typcial generators you will run into. It is possible to develop custom generator. The interaction with the database will depend on generation strategy.
The @GeneratedValue annotation specifies how to generate values for the given column. This annotation will help in creating primary keys values according to the specified strategy. The only thing we need to do is to add @GeneratedValue annotation in the POJO class.
Annotation Type GeneratedValueProvides for the specification of generation strategies for the values of primary keys. The GeneratedValue annotation may be applied to a primary key property or field of an entity or mapped superclass in conjunction with the Id annotation.
GenerationType.It relies on an auto-incremented database column and lets the database generate a new value with each insert operation. From a database point of view, this is very efficient because the auto-increment columns are highly optimized, and it doesn't require any additional statements.
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.
It is possible to develop custom generator. The interaction with the database will depend on generation strategy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With