使用Hibernate @Index注释在DB上创建索引

Ahm*_*gle 18 java annotations hibernate hibernate-annotations database-indexes

我的项目中有注释驱动的hibernate功能.

现在我想在列上创建索引.我目前的列定义是

@NotNull
@Column(name = "hash")
private String hash;
Run Code Online (Sandbox Code Playgroud)

我在@Index这里添加注释.

@NotNull
@Column(name = "hash")
@Index(name="hashIndex")
private String hash;
Run Code Online (Sandbox Code Playgroud)

然后DROP TABLE并重启Tomcat服务器.在实例化服务器之后,会创建表,但我无法在后续查询中看到新索引.

SHOW INDEX FROM tableName
Run Code Online (Sandbox Code Playgroud)

期望用新索引构造表.我正在使用带有MySQL的InnoDB.

Ahm*_*gle 17

有趣的是,在我使用的Hibernate配置中hibernate.hbm2ddl.auto=update.

这个修改了现有的数据库.我手动DROPping表tableName并重新启动Tomcat并且已经构建了表但是没有创建索引.

不过,我做了hibernate.hbm2ddl.auto=create在Web应用程序的每个实例其重新创建数据库时,放弃我所有的数据库和重建背部和-hell yeah-我的新指数已创建!


Ste*_*lli 9

在Hibernate中故意禁用模式更新上的索引创建,因为它似乎与模式导出中使用的命名不一致.

这是您可以在课堂上找到的注释代码org.hibernate.cfg.Configuration.

//broken, 'cos we don't generate these with names in SchemaExport
subIter = table.getIndexIterator();
while ( subIter.hasNext() ) {
    Index index = (Index) subIter.next();
    if ( !index.isForeignKey() || !dialect.hasImplicitIndexForForeignKey() ) {
        if ( tableInfo==null || tableInfo.getIndexMetadata( index.getFilterName() ) == null ) {
            script.add( index.sqlCreateString(dialect, mapping) );
        }
    }
}
//broken, 'cos we don't generate these with names in SchemaExport
subIter = table.getUniqueKeyIterator();
while ( subIter.hasNext() ) {
    UniqueKey uk = (UniqueKey) subIter.next();
    if ( tableInfo==null || tableInfo.getIndexMetadata( uk.getFilterName() ) == null ) {
        script.add( uk.sqlCreateString(dialect, mapping) );
    }
}
Run Code Online (Sandbox Code Playgroud)

通常我删除该注释,重新编译Hibernate.jar并在架构更新时创建索引而没有任何问题,至少对于Oracle DB.

在最近的Hibernate版本中,第一部分(表索引)的注释也已在官方版本中删除,而它仍然评论第二部分(实现唯一键的索引).请参阅http://opensource.atlassian.com/projects/hibernate/browse/HHH-1012上的讨论

  • 只是为了备份这个答案 - 更新数据库以创建索引对我来说是使用hibernate 4.1.3和mysq.如果我向实体添加@Index注释,则会自动为我创建索引而不删除和重新创建表. (2认同)