I'm really finding it hard to understand why is @generatedValue is used for auto incrementing when the table is already providing auto_increment. Can some please explain this to me.
-
1It tells the ORM framework to fetch the next value from the sequence generator before persisting the record. – The Head Rush May 15 '19 at 19:19
-
@TheHeadRush could you please explain it to me in layman's term. – user11423673 May 15 '19 at 19:27
-
please refer this [https://stackoverflow.com/questions/20603638/what-is-the-use-of-annotations-id-and-generatedvaluestrategy-generationtype](https://stackoverflow.com/questions/20603638/what-is-the-use-of-annotations-id-and-generatedvaluestrategy-generationtype) – siddharthkumar patel May 15 '19 at 19:33
1 Answers
@GeneratedValue
is used to inform JPA provider that particular field should receive generated value. Then based on GenerationType
passed to @GeneratedValue
annotation, provider will decide how to assign values to primary keys, for example by delegating it to some database mechanism.
For example oracle databases require sequences to get generated values for primary keys so in case of using oracle database you would pass GenerationType.SEQUENCE
to @GeneratedValue
, and you will also have to create such sequence.
In case of MySQL databases you would pass GenerationType.IDENTITY
and underneath it would use AUTO_INCREMENT
of primary key column in your MySQL table.
As documentation for GenerationType.IDENTITY
says :
IDENTITY Indicates that the persistence provider must assign primary keys for the entity using a database identity column.
We need all those annotations because JPA is just an abstraction for working with relational databases and it can work with different databases which use different mechanism undearneath. Hibernate is just one of implementations of JPA.

- 15,659
- 4
- 36
- 63
-
So what I understood is suppose we are using @generatedvalue(strategy=generationType.IDENTITY) on private int id; then it will get the value for ID from the MySQL table with auto_incremented colum ID. Please correct me if I'm wrong. – user11423673 May 16 '19 at 14:07
-
Yes, you are right. As `@Id` annotation is used on fileds which represent primary keys, `@GeneratedValue` is used on the same field to instruct JPA provider how primary keys should be genertated (in case of MySQL and using `GenerationType.IDENTITY`, they will be generated by AUTO_INCREMENT property of column in corresponding table). – Michał Krzywański May 16 '19 at 14:34
-