问题描述:

Hi iam creating two table in mysql for onetoone mapping in spring hibernate,but i am getting the error ERROR 1215 (HY000): Cannot add foreign key constraint

This is my first table

CREATE TABLE `Employee` ( `empId` int(11) NOT NULL,

`empName` varchar(255) DEFAULT NULL, `empExp` int(11) NOT NULL,

`empTeam` varchar(255) DEFAULT NULL, `teamId` int(11) DEFAULT NULL);

second table

CREATE TABLE `EmpTeam` ( `teamId` int(11) NOT NULL,

`teamName` varchar(255) DEFAULT NULL, PRIMARY KEY (`teamId`) ,

KEY `FK1` (`teamId`), CONSTRAINT `FK1` FOREIGN KEY (`teamId`)

REFERENCES `Employee` (`empId`));

Please help,thanks in advance

网友答案:

try this

  CREATE TABLE `EmpTeam` (  `teamId` int(11) NOT NULL, 
                            `teamName` varchar(255) DEFAULT     NULL,
                             PRIMARY KEY (`teamId`)  ,
                             CONSTRAINT `FK1` FOREIGN KEY (`teamId`) 
                             REFERENCES `Employee`   (`empId`));

if you already have this FK1 then remove it and create it again:

   alter table `EmpTeam` drop foreign key `FK1`

EDIT:

you have to add PRIMARY KEY also in your Employee table . and it should work.

change this

   CREATE TABLE `Employee` (  `empId` int(11) NOT NULL ,

to

   CREATE TABLE `Employee` (  `empId` int(11) NOT NULL  PRIMARY KEY ,
相关阅读:
Top