Win a copy of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications this week in the Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Saving Parent having multiple Child row refering Multiple parents gives Foreign Key constrain  RSS feed

Manish Jaju
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I am using JPA/EJB3.0 to persist data.
I have a parent entity p1, which has list of Child entity c1,c2.. Child has foreign keys one of them refering to p1's primary key and other is refering to other entity s's primary key.
When I save p1, it gives me error "Cannot add or update a child row: a foreign key constraint fails"

The problem is that p1 is not saved yet i.e. its a new object and its PK is not available till it is saved.
How can I assign foreing key value in child entity which is refered from parent p, which is not saved.
I did try this, but it didn't work

Parent1 p = new Parent1();
Parent2 s= entityManager.find(Parent2.class,1);
Set<Child> cs= new Hashset<Child>();
Child c1= new Child();
c1.setParent1Id(0); //which is Parent1's PK
c1.setParent2Id(s.getId) // which is Parent2's PK


I did try to set Parent1's PK value to -1 in child object. But It didn't work.
Am I missing something which is causing this problem..

Any help would appreciated.


  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!