1

In my project, I use hibernate and there is an object that has at least 30 references to other objects which are entities as well.

Of course it's not possible to just call

session.save(myHeavyObj);

Because it will throw "object references an unsaved transient instance".

I want to persist all objects. Is there any easy way to persist one object that contains many references to other entities objects?

UPDATE

@Entity
class MyClass{
     //basic elements
     @ElementCollection
     @OneToMany(cascade=CascadeType.ALL) //some don't have this line
     @LazyCollection(LazyCollectionOption.FALSE)
     List<Medication> allMeds = new ArrayList<Medication>(); //Medication is Entity

    //and more lists like this. 
}

SOLUTION

It worked by adding

 @OneToMany(cascade=CascadeType.ALL)
Mohamed Taher Alrefaie
  • 15,698
  • 9
  • 48
  • 66
  • Do you want to persist the other entities as well or not? Sorry, not clear from the question. – James Mar 21 '13 at 19:40
  • Yes. I want to persist them all. And according to my very limited knowledge, I have to persist them one by one which is not feasible since I have around 30 references inside the object. Sorry for not being clear. – Mohamed Taher Alrefaie Mar 21 '13 at 19:59
  • Could you post a sample of you root entity? Gavin has a suggestion on the Cascade type below but I'm not sure that this is all of your problem. – James Mar 21 '13 at 20:01
  • I added code sample as suggested. – Mohamed Taher Alrefaie Mar 21 '13 at 20:06
  • 1
    Someone else asked this question before: http://stackoverflow.com/questions/2302802/object-references-an-unsaved-transient-instance-save-the-transient-instance-be – James Mar 21 '13 at 20:10

1 Answers1

3

You could set the CascadeType property to PERSIST or ALL on your relationship annotations. This will tell hibernate what actions to "cascade" to the other entities. This will look like

@Entity
public class MyEntity{
    @OneToOne(cascade = CascadeType.PERSIST)
    private MyOtherEntity otherEntity;
}
GuessBurger
  • 478
  • 4
  • 9