开发者

Is it possible to create indices on join table using Hibernate annotations and hbm2ddl?

开发者 https://www.devze.com 2022-12-19 11:06 出处:网络
I have a two entities in many-to-many association. Hibernate creates a join table for this association if hbm2ddl is activated. However, since I do not have an entity for this table, I can not apply @

I have a two entities in many-to-many association. Hibernate creates a join table for this association if hbm2ddl is activated. However, since I do not have an entity for this table, I can not apply @Index annotation. Is there a way to te开发者_如何学运维ll hibernate hbm2ddl to generate indices and primary key on the join table?


One option is to use auxiliary database objects, but it would require you to switch from JPA annotations to a traditional .hbm.xml file.

Here is an example:

<!-- 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>

Another option is to just bite the bullet and create a full-fledged entity to replace the join table. This is in fact what I did in a similar situation.

Hope this helps.


You could apply index on a collection table annotation. E.g.:

    @javax.persistence.ElementCollection(fetch = javax.persistence.FetchType.LAZY)
@javax.persistence.CollectionTable(
        name = "TheJoinTable",
        indexes = {
            @Index(name = "MyIndex", columnList = "Entity1ID")},
         joinColumns = {
            @JoinColumn(name = "TheJoinColumn")}
)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号