数据引起的外键问题
最近工程启动时总是有异常,提示建立外键失败,如下所示:
ERROR org.hibernate.tool.hbm2ddl.SchemaUpdate - HHH000388: Unsuccessful: alter table advice add constraint FK_spyt7h4wq909se0kyopquuvuv foreign key (company_id) references company (id)
ERROR org.hibernate.tool.hbm2ddl.SchemaUpdate - Cannot add or update a child row: a foreign key constraint fails (credithr
.#sql-5cb5_9bcb
, CONSTRAINT FK_spyt7h4wq909se0kyopquuvuv
FOREIGN KEY (company_id
) REFERENCES company
(id
))
Advice中如下定义:
class Advice {
Company company
static belongsTo = [Company]
}
Company中如下定义:
class Company {
static hasMany = [
advices:Advice
]
}
想了好久也没有发现问题所在,明明平时就是这么定义的(明明是谁?哈哈哈)。。。偶然间网上发现了一篇文章,找到了原因,因为Advice表中companyId的外键是我后来加的,开发的童鞋嫌麻烦,测试时随意给了个0,但是Company表中木有id为0的数据,汗一个先。。。
解决方法:companyId赋值正确就可以了,脏数据惹的祸啊(抓狂状。。。)
参考:http://www.cnblogs.com/lyr-notebook/p/5419549.html