.jdbc4.MySQLIntegrityConstraintViolationException:

2019-09-05 02:22发布

问题:

I am following up a tutorial from this

url http://hellokoding.com/registration-and-login-example-with-spring-xml-configuration-maven-jsp-and-mysql/

I have three entities in my database namely user, role and role_user. role_user has a foreign key to user and role tables respectively as shown in the picture below

Everything works fine but immediately I try to create a new user I have an error Cannot add or update a child row: a foreign key constraint fails

This is the full stacktrace

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`accounts`.`user_role`, CONSTRAINT `user_role_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    com.mysql.jdbc.Util.handleNewInstance(Util.java:400)
    com.mysql.jdbc.Util.getInstance(Util.java:383)
    com.mysql.jdbc.SQLError.createSQLException(SQLError.java:973)

Please what could be wrong?

回答1:

Have you made sure that the user_id & role_id are defined as primary keys and enable auto increment. As corrected below:

CREATE TABLE `user_role` (
  `user_id` int(11) NOT NULL,
  `role_id` int(11) NOT NULL,
  PRIMARY KEY (`user_id`,`role_id`),
  KEY `fk_user_role_roleid_idx` (`role_id`),
  CONSTRAINT `fk_user_role_roleid` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `fk_user_role_userid` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Above is the user_role table. If you try to insert another user_id 6 with role_id 1, it will fail with the below: