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.  [ 3 posts ] 
Author Message
 Post subject: NHibernate newbie - Copying records
PostPosted: Fri Aug 15, 2008 11:48 am 
Newbie

Joined: Fri Aug 15, 2008 11:39 am
Posts: 3
Hi

Creating the domain objects and adding data to my database using ISession.SaveOrUpdate() works great.

My problem is I cannot figure out how to copy records. I have found the following example code:

Code:
session.Evict(product);
product.Id = 0;
session.SaveOrUpdate(product);


Is this the best way to do it? What would happen if I had a many-to-one relationship scenario and tried the same code, would it work?

Thanks!


Top
 Profile  
 
 Post subject:
PostPosted: Sun Aug 17, 2008 8:32 am 
Newbie

Joined: Fri Aug 15, 2008 11:39 am
Posts: 3
Another method would be to close and reopen the session so I can make changes to the product object:

Code:
session.Close();
session.OpenSession();
product.Id = 0;
session.SaveOrUpdate(product)


Both of these methods didn't seem right and I have gone down the route of deep cloning my product object (using serialization), setting its Id to 0 (to avoid any clashes in my table) and persisting it back using the session object.

This work great until you start building one-to-one relationships and need to clone each child object individually and reset their Id's to 0.

I'd just like to know that the method of keeping a constant session, cloning my domainobjects, resetting their key field to 0 and persisting them back is the correct/best/preferred way of copying records in a database?

Many Thanks!


Top
 Profile  
 
 Post subject:
PostPosted: Mon Aug 18, 2008 9:37 am 
Newbie

Joined: Mon Aug 18, 2008 9:29 am
Posts: 1
You could, probably implement ICloneable interface and copy the object by yourself or in Burrow project there is helper: " to clone objects using Serialization" which is in fact like:
Code:
       
public static object Clone(object obj, IFormatter formatter)
{
       using (MemoryStream buffer = new MemoryStream())
       {
            formatter.Serialize(buffer, obj);
            buffer.Position = 0;
            return formatter.Deserialize(buffer);
        }
}


motyl.


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

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.