我可以使用Hibernate hbm2ddl在同一个数据库中创建MyISAM和InnoDB表吗?

3

我需要在我的数据库中使用MyISAM表和InnoDB表,我正在使用hbm2ddl来创建它们。我能否使用Hibernate hbm2ddl在同一个数据库中创建MyISAM和InnoDB表?似乎选择方言会强制我使用其中之一。

1个回答

2
嗯,就像您所写的那样,如果您使用MySQL5InnoDBDialect,Hibernate会生成InnoDB表:
public class MySQL5InnoDBDialect extends MySQL5Dialect {

    public boolean supportsCascadeDelete() {
        return true;
    }

    public String getTableTypeString() {
        return " ENGINE=InnoDB";
    }

    public boolean hasSelfReferentialForeignKeyBug() {
        return true;
    }

}

使用这种方言将会导致Hibernate在CREATE TABLE语句的末尾添加ENGINE=InnoDB。但这是全局设置,无法在实体级别上调整此行为。
要同时使用hbm2ddl并混合表引擎,我的建议是在事后对特定表进行ALTER。为此,您可以使用5.7.辅助数据库对象。根据文档:

5.7. Auxiliary database objects

Auxiliary database objects allow for the CREATE and DROP of arbitrary database objects. In conjunction with Hibernate's schema evolution tools, they have the ability to fully define a user schema within the Hibernate mapping files. Although designed specifically for creating and dropping things like triggers or stored procedures, any SQL command that can be run via a java.sql.Statement.execute() method is valid (for example, ALTERs, INSERTS, etc.). There are essentially two modes for defining auxiliary database objects:

The first mode is to explicitly list the CREATE and DROP commands in the mapping file:

<hibernate-mapping>
    ...
    <database-object>
        <create>CREATE TRIGGER my_trigger ...</create>
        <drop>DROP TRIGGER my_trigger</drop>
    </database-object>
</hibernate-mapping>

The second mode is to supply a custom class that constructs the CREATE and DROP commands. This custom class must implement the org.hibernate.mapping.AuxiliaryDatabaseObject interface.

<hibernate-mapping>
    ...
    <database-object>
        <definition class="MyTriggerDefinition"/>
    </database-object>
</hibernate-mapping>

Additionally, these database objects can be optionally scoped so that they only apply when certain dialects are used.

<hibernate-mapping>
    ...
    <database-object>
        <definition class="MyTriggerDefinition"/>
        <dialect-scope name="org.hibernate.dialect.Oracle9iDialect"/>
        <dialect-scope name="org.hibernate.dialect.Oracle10gDialect"/>
    </database-object>
</hibernate-mapping>
另一个选项是滥用 Hibernate import.sql 功能来执行 ALTER

由于 JPA 规范不支持设置引擎和添加索引(除外键之外),因此运行 ALTER 脚本是可接受的。 - Oded Peer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接