I've solved this by using a long lived session...
In the method that is responsible of showing my form, I've this code
Code:
public void Execute( int id )
{
// _session is a member variable of the form.
_session = Appsettings.Instance.SessionFactoryObj.OpenSession();
_container c = (Container)_session.Get(typeof(Container), id);
_session.Disconnect();
this.Show();
}
Then,when the user clicks ok to close to form and confirm any changes he's made, this code is executed:
Code:
public void OkButtonClick()
{
if( _session.IsConnected == false )
{
_session.Reconnect();
}
_session.SaveOrUpdate (_container);
_session.Flush();
_session.Close();
this.Close();
}
(I know that this code is not very good, but it's just some test-code to get familiar with hibernate).
However, what about this approach ? Is it a good one ? What about the disadvantages of keeping the session object as long lived as the lifetime of the form (the form is just some kind of 'detail-form' where the user can see and edit information about one object (container in this case).
I've also read about detached objects. I've tried this as well (create a session in where I'll load the object, close the session; when the user wants to save its changes, create a new session, attach the object to the session (by using session.lock ), and then call SaveOrUpdate, but this doesn't seem to work very well...
Nothing gets updated, even though I've changed some things. Debugging learned me that the re-attached object contains the same values as the object that i wanted to update (I'm using .NET databinding).
When I do not make use of .NET databinding, then, it works as expected:
Code:
public void OkButtonClick()
{
ISession s = SessionFactoryObj.OpenSession();
s.Lock (_container, LockMode.None);
_container.Name = txtName.Text;
s.SaveOrUpdate (_container);
.....
}