我对h2数据库中索引名称的唯一性有一个小问题。使用mysql / mariadb,可以同时为表A和表B定义名为“X”的索引。使用h2数据库是不可能的,因为索引的名称对于每个数据库应该是唯一的。
这对我来说是一个问题,因为我有一个基础JPA实体类,定义了以下属性:
@org.hibernate.annotations.Index(name = "X")
protected String x;
它由类A和B继承,并且类B的索引创建失败,并出现以下错误:
ERROR [main] o.h.tool.hbm2ddl.SchemaUpdate - HHH000388: Unsuccessful: create index X on B(x)
ERROR [main] o.h.tool.hbm2ddl.SchemaUpdate - Index "X" already exists
是否有可能告诉hibernate自动创建索引名称或以某种方式为H2创建一个适配器,它将使用表名称为这些索引名称添加前缀?
虽然您应该始终使用database drive the schema evolution并使用FlywayDB来迁移模式版本,但您可以根据需要覆盖@Index。
我添加了一个test on GitHub来证明这一点。
这些类看起来像这样:
@Entity(name = "Base")
@Table(name="Base")
@Inheritance(strategy = InheritanceType.JOINED)
public static abstract class Base {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Transient
protected String x;
public Long getId() {
return id;
}
public String getX() {
return x;
}
public void setX(String x) {
this.x = x;
}
}
@Entity(name = "ChildY")
@Table(name="ChildY")
@DiscriminatorValue("Y")
public static class ChildY extends Base {
private String y;
@Override
@org.hibernate.annotations.Index(name = "xy")
@Access(AccessType.PROPERTY)
public String getX() {
return x;
}
}
@Entity(name = "ChildZ")
@Table(name="ChildZ")
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorValue("Z")
public static class ChildZ extends Base {
private String z;
@Override
@org.hibernate.annotations.Index(name = "xz")
@Access(AccessType.PROPERTY)
public String getX() {
return x;
}
}
架构生成如下:
create table Base (id bigint generated by default as identity (start with 1), primary key (id))
create table ChildY (x varchar(255), y varchar(255), id bigint not null, primary key (id))
create table ChildZ (x varchar(255), z varchar(255), id bigint not null, primary key (id))
create index xy on ChildY (x)
create index xz on ChildZ (x)
这条路:
x
列和相关索引问题是你不能在基类中拥有该字段,因为Hibernate将尝试创建它两次。您可以在Hibernate上提交Jira问题,并提及HBM模式生成应该跳过索引(如果它已经创建)。
最优雅的解决方案是简单地使用适当的数据库模式并删除HBM-DDL模式生成。