3

Here 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>();

}

As you can imagine there would be a table called "user_type", which has two columns, one is "user_id" and the other is "type".

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

tmarwen
  • 15,750
  • 5
  • 43
  • 62
Jian Chen
  • 586
  • 7
  • 20

2 Answers2

2

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.

Don Roby
  • 40,677
  • 6
  • 91
  • 113
  • 1
    Yes. It worked for me. Could be database-dependent I suppose. – Don Roby Mar 26 '10 at 09:50
  • Related: issues with `@Index` and `@ManyToMany`, labeled "won't fix" as there is a workaround in hibernate 4.3+ https://hibernate.atlassian.net/browse/HHH-4263 – RobertG Oct 28 '15 at 12:02
1

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

Ajay
  • 763
  • 5
  • 17
  • 1
    I pulled the sources today, and cannot confirm this - the method is overridden by MySQL dialect, but there seems to be no code to add an index https://github.com/hibernate/hibernate-orm/blob/master/hibernate-core/src/main/java/org/hibernate/dialect/MySQLDialect.java – RobertG Oct 28 '15 at 11:56
  • Instead, MySQL seems to add indices automatically if you use the InnoDB dialect, according to this post http://stackoverflow.com/a/1145183/1143126 – RobertG Oct 28 '15 at 11:58
  • _If neither a CONSTRAINT symbol or FOREIGN KEY index_name is defined, the foreign key index name is generated using the name of the referencing foreign key column._ [link](http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html) – RobertG Oct 28 '15 at 12:10