我的项目上有注释驱动的冬眠胶囊。

现在,我想通过一列创建索引。我当前的列定义是

@NotNull
@Column(name = "hash")
private String hash;

我补充 @Index 在这里注释。

@NotNull
@Column(name = "hash")
@Index(name="hashIndex")
private String hash;

然后丢弃表并重新启动Tomcat服务器。实例化服务器后,创建了表,但是在以下查询时我看不到新的索引。

SHOW INDEX FROM tableName

预计将使用新索引构建表。我正在与mySQL一起使用InnoDB。

有帮助吗?

解决方案

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

这个修改现有数据库。我在手动放桌子 tableName 重新启动Tomcat和桌子已经构造,但没有创建索引。

但是,我做了 hibernate.hbm2ddl.auto=create 它重新创建了WebApp的每个实例化的数据库,它删除了我所有的数据库并重新构成了,并且-hell是的 - 我的新索引已创建!

其他提示

在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) );
    }
}

通常,我删除该评论,重新编译Hibernate.jar并在架构更新上创建索引,至少没有任何问题,至少使用Oracle DB。

在冬眠的最新版本中,对第一部分的评论(表索引)也已在官方版本中删除,虽然仍然对第二部分(实现唯一键的索引)进行了评论。看到讨论 http://opensource.atlassian.com/projects/hibernate/browse/hhh-1012

更好的DB设计意味着模式由与数据本身不同的用户所有。因此,我设置了 hibernate.hbm2ddl.auto=none 因此,冬眠开始时没有失败。我改用schemaprinter。可以通过我喜欢的SQL工具运行其输出,以便在需要时重新创建模式。

import java.io.IOException;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class SchemaPrinter {

    public static void main(String[] args) throws IOException {

        Configuration cfg = new AnnotationConfiguration()
            .addAnnotatedClass(MyClass1.class)
            .addAnnotatedClass(MyClass2.class)
            .setProperty(Environment.USER, "user")
            .setProperty(Environment.PASS, "password")
            .setProperty(Environment.URL, "jdbc:sybase:jndi:file://sql.ini?mydb")
            .setProperty(Environment.DIALECT, "org.hibernate.dialect.SybaseASE15Dialect")
            .setProperty(Environment.DRIVER, "com.sybase.jdbc4.jdbc.SybDriver")
            .setProperty(Environment.HBM2DDL_AUTO, "none")
        SchemaExport exp = new SchemaExport(cfg);
        exp.setOutputFile("schema.ddl");
        exp.create(true, false);
    }

}

在Hibernate 3.5.6中使用 <property name="hibernate.hbm2ddl.auto">update</property>创建索引。因此,现在一个正确的答案是升级。但是我将这个答案留给那些遇到这个问题的人。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top