首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何修复"java.sql.SQLException:无法添加外键约束“。创建具有双主/外键关系的表时

如何修复"java.sql.SQLException:无法添加外键约束“。创建具有双主/外键关系的表时
EN

Stack Overflow用户
提问于 2019-04-05 23:03:17
回答 1查看 613关注 0票数 2

我正在为我正在使用Kotlin和Jetbrain的公开SQL库的项目建立一个数据库。我试图在两个表( cw_cache (父表)和cw_requests (子表))之间建立外键关系。

此设置在Sqlite数据库中运行良好,但当我试图在MySQL服务器数据库中创建表时,该设置不起作用。我得到错误"java.sql.SQLException:无法添加外键约束“。

我已经研究过类似的问题,并确保父表和子表中的列具有相同的数据类型,父表中的列实际上是键,并且cw_cache表是在cw_requests表之前创建的。

当我运行SHOW ENGINE INNODB STATUS;来查看外键错误时,我会看到以下内容:

代码语言:javascript
复制
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2019-04-05 18:29:17 2e94 Error in foreign key constraint of table coursewatcher/cw_requests:
FOREIGN KEY (term) REFERENCES cw_cache(term) ON DELETE RESTRICT ON UPDATE RESTRICT):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
for correct foreign key definition.

Sqlite数据库中的图表:https://gyazo.com/220dd4b1a3d301419e0b8b73bfc80a68

有关守则:

cw_cache表:

代码语言:javascript
复制
object Cache : Table("cw_cache") {
    val crn = varchar("crn", 5).primaryKey()
    val term = varchar("term", 6).primaryKey()

    // other column initializers
}

cw_request表:

代码语言:javascript
复制
object Requests : Table("cw_requests") {
    val id = long("id").primaryKey()
    val orderId = long("order_id") references Orders.id
    val crn = varchar("crn", 5) references Cache.crn
    val term = varchar("term", 6) references Cache.term

    // other column initializers
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-05 23:13:54

根据以下问题,声明复合外键目前没有使用公开的框架实现:https://github.com/JetBrains/Exposed/issues/511

关于这个问题的答复给出了一个手动解决方案的代码示例:

代码语言:javascript
复制
val t = TransactionManager.current()
val fk = ForeignKeyConstraint("fk_name",
                    t.identity(TableA), "{t.identity(TableA.idA)}, {t.identity(TableA.idA)}",
                    t.identity(TableB), "{t.identity(TableB.idA)}, {t.identity(TableB.idA)}",
                    ReferenceOption.RESTRICT,
                    ReferenceOption.RESTRICT)
t.exec(fk.createStatement().firsts())

我没有使用Kotlin或公开的框架,所以不要问我如何使用这个代码示例。如果这对你有意义,祝你好运。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55544341

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档