Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hibernate - Updating a newly created entity... that's in memory, not in db yet.

 
Chris Montgomery
Ranch Hand
Posts: 141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So wondering if this is even possible...

Setup:
Member Entity
Address Entity
OneToMany @Jointable -> MemberAddress (magically updated)
(I'm using annotations and spring, no cfg.xml files)

'Enhancement':
MemberAddress is also an Entity because I have add'l fields in it.

Issue:
Just after I create the Member with Address data in it (which, as mentioned earlier, automagically inserts the MemberAddress record), I sometimes need to update the newly created MemberAddress entity.
Regretfully, the newly created MemberAddress entity is still in memory and not physically in the db yet (not in db, fetch returns null).
Thus, I cannot update it.

Am I dreaming or can I actually get at the newly created Entity in memory and update the add'l field?

getSession().flush() kept coming up in Googie, but no luck.

Thanks!
 
Chris Montgomery
Ranch Hand
Posts: 141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Figured it out.

In my setup, the Member already Exists and the Address already exist. But the Union of the two hadn't happended yet.
I do that later and the OneToMany @Jointable magic populates the MemberAddress table when I call member.getAddresses().add(new Address).

Once member.getAddresses().add(address) was called, I was actually executing a Hibernate create statement to update the Member entity (which actually does do an update).
This is where my issue surfaced. A create does not call a Session.flush(), which updates the physical db with what is in memory (rollbacks can still happen). Since I'm in a transaction, everything is taking place in memory, so my attempt to obtain that newly created MemberAddress record wasn't possible.

Only when the transaction was fully committed by Spring would the phisical database get updated with the newly created MemberAddress record.

The fix is to call a Hibernate update rather than a create.
Once I did this, everything appeared as hoped!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic