You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot从Model创建Entity失败问题求助

Spring Boot Entity创建SQL语法错误解决方案

问题场景

在Spring Boot项目中使用H2数据库,通过JPA从Entity生成表结构时出现SQL语法错误。

实体类代码

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import lombok.Data;

@Data
@Entity
public class Order {
    @Id
    private Long id;
    private double price;
}

数据库配置(application.properties)

# Database configuration
spring.datasource.url=jdbc:h2:file:./database
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=dsamgroup1
spring.datasource.password=43HJ23jlkm456ndY
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

# Update schema when database changed
spring.jpa.hibernate.ddl-auto=update

# Enabling H2 Console
spring.h2.console.enabled=true

# Custom H2 Console URL
spring.h2.console.path=/h2-console

spring.jpa.show-sql=true

控制台错误日志

WARN 8513 --- [  restartedMain] o.h.t.s.i.ExceptionHandlerLoggedImpl     : GenerationTarget encountered exception accepting command : Error executing DDL "create table order (id bigint not null, price float(53) not null, primary key (id))" via JDBC Statement

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table order (id bigint not null, price float(53) not null, primary key (id))" via JDBC Statement
    at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    ...
Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement "create table [*]order (id bigint not null, price float(53) not null, primary key (id))"; expected "identifier"; SQL statement:
create table order (id bigint not null, price float(53) not null, primary key (id)) [42001-214]
    ...

错误原因

Order是H2数据库的关键字,直接将其用作表名会触发SQL语法解析错误。

解决方案

方案1:指定非关键字表名

在Entity类上添加@Table注解,指定一个合法的表名(比如orders):

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.Data;

@Data
@Entity
@Table(name = "orders")
public class Order {
    @Id
    private Long id;
    private double price;
}

方案2:保留原表名并转义

如果必须使用order作为表名,可以通过反引号包裹表名进行转义(H2数据库支持该语法):

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.Data;

@Data
@Entity
@Table(name = "`order`")
public class Order {
    @Id
    private Long id;
    private double price;
}

内容的提问来源于stack exchange,提问作者Sulaiman Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 17:25:26