• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hibernate cascading save not working as expected

 
James Adams
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an entity class A with a one-to-many relationship to another entity class B. The column which specifies this relationship specifies CascadeType.PERSIST and CascadeType.MERGE. My understanding was that if I create a new object of type A, create a new object of type B, and insert the object B into object A then when I save object A I will also have object saved as well by virtue of having configured cascading save for the object B collection field within A.

For example:



So if I have some code which does something like this:



then I am expecting for both a and b to be persisted since cascading saves have been configured on A's bList field. However this isn't happening, I get an exception from Hibernate telling me that I need to first save the transient instance of B:



Can anyone explain why this happens and why I am mistaken? Obviously I have misunderstood how cascading saves are supposed to work, or how to configure it correctly, etc.

Thanks in advance for any suggestions!

--James
 
James Adams
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I may have the answer, which I'll confirm tomorrow once I'm back at work -- I think I was mistaken in my thinking that CascadeType.PERSIST works for any operation that persists an entity, such as a save() call, but it probably only cascades the effect of calling persist(). The CascadeType I need to be using is Hibernate's CascadeType.SAVE_UPDATE, which will cascade the effects of calling save() or saveOrUpdate(). I'll follow up this post with my findings...

--James
 
James Adams
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My troubles went away once I added the below CascadeType setting to the collection field:

@org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)

I hope this helps someone facing this issue in the future.

--James
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic