Hibernate version:
NHibernate 1.0.2.0
Reported Exception Message: {"a different object with the same identifier value was already associated with the session: 44, of class: BeautifulMinds.everythingsGreen.Core.Campaigns.CampaignerRealtimeData" }
Stack Trace: " at NHibernate.Impl.SessionImpl.CheckUniqueness(Key key, Object obj)\r\n at NHibernate.Impl.SessionImpl.DoUpdateMutable(Object obj, Object id, IClassPersister persister)\r\n at NHibernate.Impl.SessionImpl.DoUpdate(Object obj, Object id, IClassPersister persister)\r\n at NHibernate.Impl.SessionImpl.SaveOrUpdate(Object obj)\r\n at everythingsGreen.Customer.Tests.ActiveUserNonThreaded._Execute() in x:\\dotnet\\web\\everythingsgreen\\source\\everythingsgreen\\everythingsgreen.customer.tests\\singleclientontosingleclassthatpersistswithoutthreadingtest.cs:line 199" string
Detail:
I havent included all the requested pre-requisites for posting a message because I think the reason to my problem is more understanding other than anythingelse.
Everytime I need to hit the database in a for-loop, I acquire a session:
Code:
private void CreateSession()
{
if(_session == null)
{
_session = _sessionFactory.OpenSession();
}
else
_session.Reconnect();
}
I either create a new one or reconnect.
I then get data attributes from multiple places and create an object named CampaignerRealtimeData - this object is to be persisted by NHibernate, and is a simple dumb-data-object with a primary key field.
The important issue here is that everytime the for-loop begins a cycle, attributes are acquired and a [b]new/[b] CampaignerRealtimeData object is created. This means I can logically do this:
Code:
for(int i = 0; i < _itemsToProcess; i++) {
CampaignerRealtimeData data = GetRealtimeData();
CreateSession();
GetSession().SaveOrUpdate(data);
}
public CampaignerRealtimeData GetRealtimeData() {
return new CampaignerRealtimeData(27, GetNumberOfVisits());
}
Here GetRealtimeData just returns the an object which always has the same primary key of 27, but GetNumberOfVisits will have changed - this obviously requires an update to the database.
The program I am building is a simulator for a real-life multithreaded enterprise system that receives data across communication channels such as TCP/IP, Email or some other mechanism. The data comes in, and a CampaignerRealtimeData object needs to be created so that it can then be persisted in the database. In this simplistic code it clearly doesnt make sense to keep creating what is essentially the same object. In the reallife situation, the time between calls could be days, and with other constraints I dont wish to cache the objects in memory. I want to keep the design simple, and this design works perfectly until I use it with NHibernate; I am positive its not NHibernate thats the problem but how I am using it.
If I dont use Reconnect/Disconnect and instead use OpenSession/Close, the code works, but I read that the former approach is much more efficient.
Thanks,
Nick.