java - 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.
解决方案
@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.
推荐阅读
- mysql - SQL:查找“新用户”与“回访用户”的比例
- r - 如何映射R中数据框中的列表列表?(tidyverse 管道)
- matlab - 如何在 MATLAB 中优化此冒泡排序算法,或用其他更有效的方法替换它?
- hololens - HoloLens 1 停止通过 Wi-Fi 连接到 PC
- autohotkey - AutoHotKey - 乘以变量不起作用
- excel - 通过 VBA 使用 XLOOKUP
- python - 使用 Python 和 Azure 函数将 URL 参数保存为 CSV 文件
- javascript - 如何使用侧面下拉菜单将滚动添加到固定的左侧栏
- javascript - 即使实现了 .setOffset(),使用功能组件创建的动画 PanResponder 也会跳转动画
- c++ - 如何将 OpenCV 与 MATLAB for macOS 链接