首页 > 解决方案 > If the database table column is set with auto_increment then why are we using @generatedValue

问题描述

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.

标签: javamysqlhibernatehibernate-mapping

解决方案


@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.


推荐阅读