MySQL - Hibernate不会创建外键约束

时间:2014-04-21 08:21:59

标签: java mysql hibernate foreign-keys innodb

我是,将我的应用程序从Derby移动到MySQL,并面临hibernate在最初创建表时不会创建外键约束的问题。我所有的映射似乎都是正确的,因为它们与Derby一起工作正常。

我正在使用MySQL Server 5.6,以及MySQL5InnoDBDialect。我还在MySQL工作台中使用show create table命令验证了该表是使用innoDB引擎创建的。

使用MySQL连接器 - mysql-connector-java - 5.1.6

日志:

2014-04-21 12:38:29,820 ERROR org.hibernate.tool.hbm2ddl.SchemaExport - Unsuccessful: alter table DEPENDENCY_TRACK add constraint FK25E3373737E62D9A foreign key (TOOL_ID) references TOOL_MASTER
2014-04-21 12:38:29,820 ERROR org.hibernate.tool.hbm2ddl.SchemaExport - Cannot add foreign key constraint
2014-04-21 12:38:30,127 ERROR org.hibernate.tool.hbm2ddl.SchemaExport - Unsuccessful: alter table DEPT_ROLE add constraint FK7E895E3080D96D8 foreign key (DEPARTMENT_ID) references DEPARTMENT
2014-04-21 12:38:30,128 ERROR org.hibernate.tool.hbm2ddl.SchemaExport - Cannot add foreign key constraint

Persistance.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
    <persistence-unit name="hibernatePersistenceUnit" transaction-type="RESOURCE_LOCAL">
        <properties>
            <property name="hibernate.hbm2ddl.auto" value="create" /> 
            <!-- <property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect" /> -->
            <!-- <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" /> -->
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
            <property name="hibernate.show_sql" value="true"/>
            <property key="hibernate.hbm2ddl.import_files">import.sql</property>
        </properties>
        <mapping-file>META-INF/orm.xml</mapping-file>
    </persistence-unit>
</persistence>

database.properties

# database properties
app.jdbc.driverClassName    =   com.mysql.jdbc.Driver
app.jdbc.url                =   jdbc:mysql://localhost:3306/alt
app.jdbc.username           =   root
app.jdbc.password           =   root

1 个答案:

答案 0 :(得分:0)

根据MySQL参考documentation for FOREIGN KEY Constraints,外键定义符合以下条件:

  

InnoDB允许外键引用任何索引列或组   列。但是,在引用的表中,必须有一个索引   其中引用的列被列为的第一列   同样的顺序。

相关问题