1

Continuing to the post of reading-from-XML-and-storing-the-values-in-database-using-grails

am facing an another problem in it. As the employee id is related to other tables as foreign key how am suppose to insert the data into the database without conflict what i want to add in grails code to avoid the below displayed error.

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:Cannot add or update a child rowL a foreign key constraint fails.. ( CONSTRAINT 'EMPLOYEE_ID_HEADER' FOREIGN KEY ('EMPLOYEE_ID') REFERENCES 'employee_header'('employee_id'))

here employee_id is a column and employee_header is a separate table that contains employee_id as a foreign key.

Community
  • 1
  • 1
Sabarish
  • 1,184
  • 3
  • 14
  • 35

1 Answers1

1

Finally I got the answer, when you are inserting the values in database the related foreign key tables will get affects initially. So to handle this situation we have to insert the foreign key related table at first then the table we need to add exactly.

For the reference, at first I had given the code like this

sql.executeInsert("insert into order_item (order_id,product_id,
order_item_seq_id) values (${order_id},${product_id},${order_item_seq_id})")

sql.executeInsert("insert into product(product_id) values(${product_id})")

This first inserts the order_item table then the foreignkey constraint table product, so the data did not inserted. So the correct code is

sql.executeInsert("insert into order_header(order_id) values(${order_id})") sql.executeInsert("insert into product(product_id) values(${product_id})") sql.executeInsert("insert into order_item (order_id,product_id,
order_item_seq_id) values (${order_id},${product_id},${order_item_seq_id})")

Now this inserts the data successfully without errors.

gnat
  • 6,213
  • 108
  • 53
  • 73
Sabarish
  • 1,184
  • 3
  • 14
  • 35