我在Java Sping Boot 项目中有一个类:
@Entity
@Table(name = "attribute_table")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Attribute {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@Column(name = "attribute_type")
private AttributeType attributeType;
@Column(name = "value")
private byte[] value;
@ManyToOne
@JoinColumn(name = "asset_category_id")
private AssetCategory assetCategory;
}
运行后,我得到一个异常:
org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement "create table test1234 (attribute_type tinyint check (attribute_type between 0 and 3), asset_category_id bigint, id bigint generated by default as identity, name varchar(255), [*]value varbinary(255), primary key (id))"; expected "identifier";
我发现当表的名称与保留的sql关键字相同时会发生这种类型的错误,但我尝试了几个@Table注解的名称,这显然不是原因。
我不知道这是否重要,但在我的Attribute类中,我有value
字段,它是byte[],因为它的类型依赖于AttributeType枚举。AssetCategory中还有一个BaseClass categoryOf
,它没有明确定义,因为它可以与其他继承自BaseClass的类Map。以下是我的项目中的其他类:
@Entity
@Table(name = "asset_categories")
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class AssetCategory {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Lob
@Column(name = "description")
private String description;
@OneToMany(mappedBy = "assetCategory")
private List<Attribute> attributes;
@OneToOne(mappedBy = "assetCategory")
private BaseClass categoryOf;
public void addAttribute(Attribute attribute) {
attributes.add(attribute);
}
}
@Getter
@Setter
@Entity
public abstract class BaseClass {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
protected Long id;
@Column(name = "name")
protected String name;
@OneToOne
@JoinColumn(name = "asset_category", referencedColumnName = "id")
protected AssetCategory assetCategory;
@Column(name = "archived")
protected Boolean archived;
}
public enum AttributeType {
NUMBER,
STRING,
DATE,
BOOL
}
2条答案
按热度按时间q8l4jmvw1#
VALUE
是SQL标准中的保留字,它是H2中的关键字,不能将其用作无引号标识符。最好为列选择一些不同的名称,但您可以使用
name = "\"VALUE\""
引用此名称,或者您可以使用spring.jpa.properties.hibernate.globally_quoted_identifiers=true
强制Hibernate ORM引用所有标识符。在最坏的情况下,您可以将
;NON_KEYWORDS=VALUE
添加到JDBC URL(如果您使用H2进行单元测试,您还需要禁用其自动配置,否则您的自定义连接URL将被忽略),但此设置并不涵盖所有可能的情况,例如在ALTER TABLE … ADD … UNIQUE(VALUE)
定义中,VALUE
仍将具有特殊含义(整行上的唯一约束)。ergxz8rk2#
如果你正在使用mysql值是一个保留的关键字,所以你可能想改变值列名称