Lesser Known NHibernate Session Methods
- by Ricardo Peres
The NHibernate ISession, the core of NHibernate usage, has some methods which are quite misunderstood and underused, to name a few, Merge, Persist, Replicate and SaveOrUpdateCopy. Their purpose is: Merge: copies properties from a transient entity to an eventually loaded entity with the same id in the first level cache; if there is no loaded entity with the same id, one will be loaded and placed in the first level cache first; if using version, the transient entity must have the same version as in the database; Persist: similar to Save or SaveOrUpdate, attaches a maybe new entity to the session, but does not generate an INSERT or UPDATE immediately and thus the entity does not get a database-generated id, it will only get it at flush time; Replicate: copies an instance from one session to another session, perhaps from a different session factory; SaveOrUpdateCopy: attaches a transient entity to the session and tries to save it. Here are some samples of its use.
ISession session = ...;
AuthorDetails existingDetails = session.Get<AuthorDetails>(1); //loads an entity and places it in the first level cache
AuthorDetails detachedDetails = new AuthorDetails { ID = existingDetails.ID, Name = "Changed Name" }; //a detached entity with the same ID as the existing one
Object mergedDetails = session.Merge(detachedDetails); //merges the Name property from the detached entity into the existing one; the detached entity does not get attached
session.Flush(); //saves the existingDetails entity, since it is now dirty, due to the change in the Name property
AuthorDetails details = ...;
ISession session = ...;
session.Persist(details); //details.ID is still 0
session.Flush(); //saves the details entity now and fetches its id
ISessionFactory factory1 = ...;
ISessionFactory factory2 = ...;
ISession session1 = factory1.OpenSession();
ISession session2 = factory2.OpenSession();
AuthorDetails existingDetails = session1.Get<AuthorDetails>(1); //loads an entity
session2.Replicate(existingDetails, ReplicationMode.Overwrite); //saves it into another session, overwriting any possibly existing one with the same id; other options are Ignore, where any existing record with the same id is left untouched, Exception, where an exception is thrown if there is a record with the same id and LatestVersion, where the latest version wins
SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/clipboard.swf';
SyntaxHighlighter.brushes.CSharp.aliases = ['c#', 'c-sharp', 'csharp'];
SyntaxHighlighter.all();