如果数据库 table 列设置为 auto_increment 那么我们为什么要使用 @generatedValue
If the database table column is set with auto_increment then why are we using @generatedValue
我真的很难理解为什么在 table 已经提供 auto_increment 时使用 @generatedValue 来自动递增。有人可以给我解释一下吗?
@GeneratedValue
用于通知 JPA 提供者特定字段应该接收生成的值。然后基于 GenerationType
传递给 @GeneratedValue
注释,提供者将决定如何将值分配给主键,例如通过将其委托给某些数据库机制。
例如,oracle 数据库需要序列来获取主键的生成值,因此在使用 oracle 数据库的情况下,您可以将 GenerationType.SEQUENCE
传递给 @GeneratedValue
,并且您还必须创建这样的序列。
如果是 MySQL 数据库,您将传递 GenerationType.IDENTITY
并在其下方使用 MySQL table 中主键列的 AUTO_INCREMENT
。
如 GenerationType.IDENTITY
的文档所述:
IDENTITY
Indicates that the persistence provider must assign primary keys for the entity using a database identity column.
我们需要所有这些注释,因为 JPA 只是处理关系数据库的抽象,它可以处理使用不同机制的不同数据库。 Hibernate 只是 JPA 的实现之一。
我真的很难理解为什么在 table 已经提供 auto_increment 时使用 @generatedValue 来自动递增。有人可以给我解释一下吗?
@GeneratedValue
用于通知 JPA 提供者特定字段应该接收生成的值。然后基于 GenerationType
传递给 @GeneratedValue
注释,提供者将决定如何将值分配给主键,例如通过将其委托给某些数据库机制。
例如,oracle 数据库需要序列来获取主键的生成值,因此在使用 oracle 数据库的情况下,您可以将 GenerationType.SEQUENCE
传递给 @GeneratedValue
,并且您还必须创建这样的序列。
如果是 MySQL 数据库,您将传递 GenerationType.IDENTITY
并在其下方使用 MySQL table 中主键列的 AUTO_INCREMENT
。
如 GenerationType.IDENTITY
的文档所述:
IDENTITY Indicates that the persistence provider must assign primary keys for the entity using a database identity column.
我们需要所有这些注释,因为 JPA 只是处理关系数据库的抽象,它可以处理使用不同机制的不同数据库。 Hibernate 只是 JPA 的实现之一。