问题描述
我有@MappedSuperClass
(简化示例):
@MappedSuperclass
public abstract class MySuperClass {
@Id
@GeneratedValue
private long id;
@Column(nullable = false)
private Date creationDate;
// ...
}
和具体的Entity
(简化示例):
and a concrete Entity
(simplified example):
@Entity
public class MyEntity extends MySuperClass {
@Index(name = "IDX_MYINDEX")
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private MyType type;
@Index(name = "IDX_MYINDEX")
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private MyResult status;
// ...
}
现在,我需要一个包含列MySuperClass.creationDate
,MyEntity.status
和MyEntity.type
的索引.
Now I need an index including the columns MySuperClass.creationDate
, MyEntity.status
and MyEntity.type
.
如果我将@Index(name = "IDX_MYINDEX")
添加到MySuperClass.creationDate
,则hibernate会将creationDate
的索引添加到从MySuperClass
继承的每个实体中.
If I add @Index(name = "IDX_MYINDEX")
to MySuperClass.creationDate
hibernate adds an index of creationDate
to every Entity inherited from MySuperClass
.
我尝试了@AttributeOverride
,但是它无法建立索引.
I tried @AttributeOverride
but it is not capable for indexes.
有什么想法吗? TIA!
Any ideas? TIA!
推荐答案
如果使用的是JPA 2.1
,则可以使用具有其属性索引的类注释@Table
If you are using JPA 2.1
then you can use class annotation @Table
with its attribute indexes
@Table(indexes = { @Index(name = "IDX_MYIDX1", columnList = "id,name,surname") })
请注意,如文档所述
如上所示,
columnlist
接受列名列表作为逗号分隔的列表.
columnlist
, as shown above, accepts column names list as a comma-delimited list.
如果您不使用JPA 2.1,则可以使用旧的Hibernate
的@Index
注释(请注意,此注释已被弃用).有一个属性columnNames
,无论在哪个字段上方声明,都可以传递列名称数组.
If you don't use JPA 2.1 you can just use old Hibernate
s @Index
annotation (note this is already deprecated). There's attribute columnNames
where you can pass array of column names no matter above which field it is declared.
@Index(name = "IDX_MYIDX1", columnNames = { "id", "name", "surname"})
这篇关于如何使用JPA/休眠创建索引,以及如何使用MappedSuperClass中的字段以及具体实体中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!