-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 
Author Message
 Post subject: MySQL Auto increment insert where autoincrement is a FK
PostPosted: Sat Oct 17, 2009 2:19 pm 
Newbie

Joined: Sat Oct 17, 2009 7:34 am
Posts: 9
Hi

The subject is confusing but let me explain
I have a MySQL DB

I have a table called BOOK whose primary key(bookID) is a auto increment field
My Book object has an attribute id which I set to 0 as mySQL knows that when doing an insert, the auto increment field will be set to zero. MySQL implicitly sets the id to the correct auto incremented value for that insert.
That all works fine

But now I have a Chapters table
whose has the following fields

bookID
chapterID
chapterDescription

bookID and chapterID make up a composite Key

Now if under all the one transaction I want to insert a record into the BOOK table and the chapter table where by the chapter table is inserting records for the record just inserted into BOOK I get a
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails

I believe this down to be the fact that my book object has an ID of zero. The insert happens into book table.
The commit hasnt happened yet but mySQL has converted zero to the next value on the book table which is fine

The chapter object has a book id attribute of 0 and hence 0 does not exist on the Book table. I debugged and my Book object hasnt yet changed the ID attribute. There has been no commit so, thats what I would expect.

This has to be a common problem for autoincrement fields in MySQL
Any advice on how to get around such an issue?

Thanks
Ally


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.