These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 
Author Message
 Post subject: Saving multiple, related objects...
PostPosted: Wed Nov 19, 2008 1:53 pm 
Newbie

Joined: Mon Nov 10, 2008 4:03 pm
Posts: 11
Hibernate version: 2.0.1GA

I'm trying to add a single record in two tables. The tables are related. I have a beginner's knowledge of NHiberate so I'm hoping there's a better way to do this.

Presently, I am under the belief that the only way I can get the ID of a newly-added record is to perform a SaveOrUpdate; then the object's ID field gets set (since I'm using autoincrement with SQL Server 2005 Express).

In order to add a record in a related table, I have to set the ID field of its parent. Here's what I'm doing now:

transaction = session.BeginTransaction();

Contact myContact = new Contact();

myContact.Company = "ABC Company";
myContact.Notes = "test";

session.SaveOrUpdate(myContact);

Address myAddress = new Address();
myAddress.IdContact = myContact.Id;
myAddress.City = "Any City";
myAddress.State = "XX";
myAddress.Zip = "12345";

session.SaveOrUpdate(myContact);

// Commit transaction
transaction.Commit();


Note that ADDRESS is related to CONTACT. 1 CONTACT per MANY ADDRESSES.

In order to add the ADDRESS record, I have to have the corresponding CONTACT ID and I believe I can only get that AFTER I create the CONTACT record, hence my use of "SaveOrUpdate" twice.

Better way out there?

Thanks!


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.