Hibernate - save some Entity in one transaction

453 Views Asked by At

I have following scenario:

  • Entity1
  • Entity2
  • Entity3
  • Entity4

Relationship:

Entity1  1...n  Entity2 
Entity2  1...n  Entity3
Entity2  1...n  Entity4

Now I have one method which should save all these entities. I use cascade for saving automatically Entity2, Entity3 and Entity4

@OneToMany(mappedBy = "entity2", cascade = { PERSIST, MERGE, REMOVE })

Currently I got following issue:

Not-null property references a transient value - transient instance must be saved before current operation

So is this scenario possible? Or should I save first Entity1 with Entity2 ?

1

There are 1 best solutions below

0
On

probably u are not setting parentEntity in child setter,i.e.you need to set class A in class B, so when it save all hierarchy in single call ,it doesn't get parent entity in mapped By column,

Class A{
    @OneToMany(mappedBy = "parent" , Cascade = cascadeType.All)
    List<B> children;

 //children setter n getter

}

Class B{

@MAnyToOne
private A parent;

SetPArent(A a){    //like this you need to set for cascade saving.
  this.parent = a;
}
}

Now Hibernate will take care of setting parent parent(foreign Id) column in child table..and it all can be save in a single save call.