简体   繁体   中英

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

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM