我想保存一些来自请求的数据。为此,我创建了一些实体类。但为什么我提出这个例外?
Error executing DDL "create table body_datum (body_datum_id integer not null, key varchar(255), value varchar(255), value_type varchar(255), primary key (body_datum_id)) engine=InnoDB" via
这是我的财产。
spring.datasource.url= jdbc:mysql://localhost:3306/loadtestdb?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create
这是我的模型课程。
@Data
@Entity
public class BodyDatum {
@Id
@GeneratedValue
private Integer bodyDatumId;
private String key;
private String value;
private String valueType;
}
产品类别是这样的
@Data
@Entity
public class Product {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Long pId;
private String productName;
private int pQty;
private int price;
@ManyToOne
@JoinColumn(name = "customer_id")
private Customer customer;
}
数据库中,Product 表已创建。
为什么会出现这样的错误?
谢谢。
我认为属性“key”是SQL的保留字。像这样重命名你的属性:
@Data
@Entity
public class BodyDatum {
@Id
@GeneratedValue
private Integer bodyDatumId;
private String bodyDatumkey;
private String value;
private String valueType;
}
我在同一条船上。
除了@RUARO提到的MySQL保留字问题之外,我还犯了另一个错误,这使得即使我用非保留字替换列名后问题仍然存在:
在
spring.datasource.url
中的application.properties
字段中,我应该在连接url的末尾指定数据库名称,即
jdbc:mysql://localhost:3306/mydatabasename
而不是
jdbc:mysql://localhost:3306
配置
application.properties
文件。
project > src > main > resources > application.properties
根据您的 Java 版本配置 Hibernate Dialect。
对于
MySql 5
使用 MySQL5Dialect
或对于 MySql 8
使用 MySQL8Dialect
像这样:
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL8Dialect
key是mysql中的保留关键字。将列名更改为其他名称,例如:“keys”——当我们在数据库中使用保留字时,通常会出现此错误。
Mysql 中的保留字 -- https://dev.mysql.com/doc/refman/8.0/en/keywords.html
参考 -- https://java.tutoriallink.com/how-to-resolve-error-executing-ddl-commands-in-spring-boot/
对键列名称使用单引号:
@Data
@Entity
public class BodyDatum {
@Id
@GeneratedValue
private Integer bodyDatumId;
@Column(name = "`key`")
private String key;
private String value;
private String valueType;
}
该问题与“table”是 PostgreSQL 中的保留关键字有关,因此在不转义的情况下不能直接用作表名。
要解决此问题,请更改表名称。
@Entity
@Table(name = "user_entity") // Change the table name to something other than "user"
public class User {
// ...
}