• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

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

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();
p.setValue1("val1");
.
.
.
Parent2 s= entityManager.find(Parent2.class,1);
Set<Child> cs= new Hashset<Child>();
Child c1= new Child();
c1.setValue1("abc");
c1.setParent1(p);
c1.setParent1Id(0); //which is Parent1's PK
c1.setParent2(s);
c1.setParent2Id(s.getId) // which is Parent2's PK
cs.add(c1);
p.add(cs);

entityManager.persist(p);


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.

Thank,
Mani

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic