首页 > 解决方案 > 为什么 Hibernate 在使用策略 GenerationType.IDENTITY 时尝试访问 hibernate_sequence?

问题描述

在我的项目中,我将 MySQL 与 Hibernate 和 JPA 一起使用。我的实体都用@ID @GeneratedValue(strategy = GenerationType.IDENTITY).

hibernate_sequence尽管如此,当将新对象插入数据库时​​,Hibernate 会尝试从表中选择下一个 ID - 这显然失败了。

我检查了整个项目是否在某个实体上意外使用了不同的生成类型,但事实并非如此。还有什么可能导致这个问题?

这是我用来创建表的 SQL:

create table versioned_string_attribute (
  id int primary key auto_increment not null,
  timestamp timestamp,
  value text
);


create table backend_address (
  id int primary key auto_increment not null,
  street_id int references versioned_string_attribute(id),
  house_number_id int references versioned_string_attribute(id),
  zip_code_id int references versioned_string_attribute(id),
  town_id int references versioned_string_attribute(id),
  addition_id int references versioned_string_attribute(id)
);

这是我的application.properties

spring.jpa.generate-ddl=false
spring.jpa.hibernate.ddl-auto=none
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.datasource.driverClassName=com.mysql.jdbc.Driver

标签: javamysqlhibernatespring-boot

解决方案


从文档(https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#common-application-properties)属性:

spring.jpa.hibernate.use-new-id-generator-mappings= # 是否对 AUTO、TABLE 和 SEQUENCE 使用 Hibernate 较新的 IdentifierGenerator。

所以我通过添加解决了这个问题spring.jpa.hibernate.use-new-id-generator-mappings=false

有关此的更多详细信息:https ://vladmihalcea.com/from-jpa-to-hibernates-legacy-and-enhanced-identifier-generators/


推荐阅读