是否可以使用Hibernate注释和hbm2ddl在连接表上创建索引?
问题描述:
我有一个多对多关联的两个实体。如果hbm2ddl被激活,Hibernate为这个关联创建一个连接表。但是,由于我没有此表的实体,因此我无法应用@Index注释。有没有办法告诉hibernate hbm2ddl在连接表上生成索引和主键?是否可以使用Hibernate注释和hbm2ddl在连接表上创建索引?
答
一个选项是使用auxiliary database objects,但它会要求您从JPA注释切换到传统.hbm.xml
文件。
下面是一个例子:
<!-- class mapping: -->
<class name="Entity1" table="Entity1">
<!-- insert other mappings here -->
<!-- this class's half of the many-to-many relationship: -->
<set name="Entity2s" table="TheJoinTable">
<key column="Entity1ID" />
<many-to-many class="Entity2" column="Entity2ID" />
</set>
</class>
<!-- auxiliary object: -->
<database-object>
<create>CREATE INDEX MyIndex ON TheJoinTable(Entity1ID)</create>
</database-object>
另一种选择是只硬着头皮创建一个完整的实体,以取代连接表。这实际上是我在类似情况下所做的。
希望这会有所帮助。
答
您可以在集合表注释中应用索引。例如:
@javax.persistence.ElementCollection(fetch = javax.persistence.FetchType.LAZY)
@javax.persistence.CollectionTable(
name = "TheJoinTable",
indexes = {
@Index(name = "MyIndex", columnList = "Entity1ID")},
joinColumns = {
@JoinColumn(name = "TheJoinColumn")}
)