Wednesday, 9 June 2010

Learn NHibernate Lesson 3 - Insert, Update and Deletes

disclaimer - at the moment, this post is in note format from a workshop I did, I need to it clean up, and add grammar

3. Insert, Update and Deletes

A Unit of work is an isolated area withing which i cna perform one or more operations. They are either commited or abandoned / rolled back as one.

As of yet we have not used nhibe to change any data. Query only. if no changes, then no commit or rollback..
Insert Pattern is simple

New up an object, ask the ISession to save it, Flush the session (flush is the commit method)[csharp]

Customer customer = new Customer();
session.save(customer);
session.Flush();

[/csharp]

Delete pattern is simple[csharp]

Customer customer = provider.GetCustomerById(1);
session.Delete(customer);
session.Flush();

[/csharp]

Update pattern

have an object
change a property
ask the session to update it
flush the sesison

primary annoyance is that you have to keep track of what objects have chnaged.. but there is a solution, ISession is able to keep track of what object are new and updated so we can call session.SaveOrUpdate and NHibe will perform the correct action. Calling saveorupdate will cause NHibe to go through some checking operatios such as:

is the object in session? if not there, call implicit Save(object);

if its there, see it the object has changed, if it has, call implicit update(object)..[csharp]

public void AddCustomer(Customer customer)
{
session.Save(customer); //save will return an object that represents the primary key of that object in the database
session.Flush();
}

[/csharp]


so you can get new primary key by saying[csharp]

int newId = (int)session.Save(customer);

[test]
public void CanAddCustomer()
{
Customer customer = new Customer() { Firstname = "steve", Lastname = "smith" };
int newId = provider.AddCustomer(customer);

Customer testCustomer = provider.GetCustomerById(newId);
Assert.IsNotNull(testCustomer);
}

public void DeleteCustomer(Customer customer)
{
session.Delete(customer);
session.Flush();
}

[test]
public void CanDeleteCustomer()
{
Customer customer = provider.GetCustomerById(1);
provider.DeleteCustomer(customer);

Customer testCustomer = provider.GetCustomerById(1);
Assert.IsNull(testCustomer);
}

[/csharp]