How can I ask Hibernate to create an index on a foreign key (JoinColumn)?

爷,独闯天下 提交于 2019-12-08 01:57:36

问题


This is my model.

class User{

   @CollectionOfElements 
    @JoinTable(name = "user_type", joinColumns = @JoinColumn(name = "user_id"))
    @Column(name = "type", nullable = false)
  private List<String> types = new ArrayList<String>();

}

You can imagin there would be a table called "user_type", which has two columns, one is "user_id", the other is "type".

And when I use hbm2ddl to generate the ddls, I can have this table, along with the foreign key constraint on "user_id". However, there is no index of this for this column. And I need this index. How can I let hibernate to generate this index for me?

Thank you!


回答1:


Try an @Index annotation.

@Index(name="user_type_index")

There is also an @IndexColumn annotation used with join tables, but it doesn't seem to actually create an index, but controls which field defines order in list semantics.

The @Index column in this context does seem to create an index on the join table.




回答2:


I'm dealing with a similar issue and I've found that some dialects will automatically index foreign keys and others wont.

Hibernate Dialect class and all subclasses which do not override the getAddForeignKeyConstraintString method (Oracle, SQL Server, etc) will not create an index on the foreign key.

MySQLDialect overrides that method and adds an index to every foreign key



来源:https://stackoverflow.com/questions/2513386/how-can-i-ask-hibernate-to-create-an-index-on-a-foreign-key-joincolumn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!