首页 > 解决方案 > Spring JPA Hibernate 无法自动生成 Id H2 表

问题描述

尝试使用自动生成的 Id 创建表时出现异常:

org.hibernate.tool.schema.spi.CommandAcceptanceException:“执行 DDL 时出错”创建表位(id bigint 不为空,描述 varchar(255),num 整数不为空,价格小数(19,2),行 char(255)不为空,主键 (id))”通过 JDBC 语句”。

看起来生成的 SQL 无法识别“@GeneratedValue(strategy = GenerationType.TABLE)”注释。看起来这是 Hibernate 或适配器的一个非常常见的问题。

现在,在您将此问题作为重复问题丢弃之前,我已经完成了所有有类似问题的 q/a 并尝试了那里建议的所有解决方案。我也尝试自己生成 Id 密钥并尝试将 spring.jpa.properties.hibernate.hbm2ddl.auto 设置为“删除创建”

应用程序属性

spring.datasource.driverClassName = org.h2.Driver
spring.datasource.username = sa
spring.datasource.password =
spring.jpa.properties.hibernate.hbm2ddl.auto=update

实体类

import java.math.BigDecimal
import javax.persistence.*

@Entity
data class Seat(
@Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="id")
                val id: Long,
                val row: Char,
                val num: Int,
                val price: BigDecimal,
                val description: String) {
    override fun toString(): String = "Seat $row-$num $$price ($description)"
}

服务构造器

constructor() {
        ...
        for (row in 1..15) {
            for (num in 1..36) {
                hiddenSeats.add(Seat(0, (row+64).toChar(), num, getPrice(row,num), getDescription(row,num) ))
            }
        }
    }

我尝试过的事情: - strategy=GenerationType.AUTO 更改为 .SEQUENCE 和 .TABLE - 将其添加到 application.properties:

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect

我试图自己生成 ID,但没有成功。我一定是缺少一些东西,因为我是新的 Kotlin、Spring Boot 和 Hibernate,但在这里碰壁了。请指教!

jdk-14,Spring Boot v2.2.6.RELEASE,使用方言:org.hibernate.dialect.H2Dialect

标签: javahibernatespring-bootjpah2

解决方案


这就是问题所在val row: Char,ROW 是 SQL 中的保留字。更改该变量


推荐阅读