我想使用hibernate创建@Index
。索引应包含3个字段,其中一些字段嵌套在其他实体中。我怎样才能做到这一点?
@Table(name = "my_entity", indexes = {
@Index(name = "my_index", columnList = "id, person.firstname, person.lastname")
})
@Entity
public class MyEntity {
private Long id;
@ManyToOne
private Person person;
}
@Entity
public class Person {
@Id private Long id;
private String firstname;
private String lastname;
}
结果:
Caused by: org.hibernate.AnnotationException: Unable to create unique key constraint (id, person.firstname, person.lastname) on table my_entity: database column 'person.firstname', 'person.lastname' not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)
at org.hibernate.cfg.Configuration.buildUniqueKeyFromColumnNames(Configuration.java:1684)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1459)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1846)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857)
... 46 more
答案 0 :(得分:2)
答案 1 :(得分:-2)
你在这里尝试做的是在2个不同的表(MyEntity和Person)上创建索引,因此这是不可能的。 如果你想这样做,你必须像这样嵌入Person类:
@Table(name = "test", indexes = {
@Index(name = "my_index", columnList = "id, person.firstname, person.lastname")
})
@Entity
public class MyEntity {
private Long id;
private Person person;
}
@Embeddable
public class Person {
private String firstname;
private String lastname;
}
请注意,我已经在Person类上通过@Embeddable重新启用了@Entity,这样在数据库中你就会有一个名为Test的表,其中包含列id,firstname和lastname