I'm trying to create a object with 4 properties; 1x ID and 3x references to other tables.
I get that I shouldn't compare a NHibernate "session.Save()" with a sql Insert statement, but I would still expect it to save it in the database, after the request/thread is done. This is what my code looks like:
var session = Home.Instance.GetSession();
session.Begin();
var profile = session.Get<ProfilePO>(profileId);
var queue = session.Get<QueuePO>(queueId);
var telephone = session.Get<TelephonePO>(telephoneId);
var newObject = new UserProfileControlledQueueMembersPO
{
Profile = profile,
Queue = queue,
Telephone = telephone
};
session.Save(newObject);
var idOfNewObj = newObject.Id; //This gets the correct value from the autoincrementing ID in the mysql database.
var newObjFromCacheOrDb = session.QueryOver<UserProfileControlledQueueMembersPO>().Where(x => x.Id == idOfNewObj).List().FirstOrDefault();
//newObjFromCacheOrDb actually return the correct values of the created object
"session" is from a wrapper class:
private int _transactionCount;
private ITransaction _transaction;
private ISession Session { get; set; }
public void Begin()
{
if (_transactionCount <= 0)
{
_transaction = Session.BeginTransaction();
_transactionCount = 0;
}
_transactionCount++;
}
public object Save<T>(T ob) where T : TEntityType
{
if (_transactionCount <= 0)
throw new Exception("Save is not allowed without an active transaction!");
return Session.Save(ob);
}
In the log for NHibernate I have found this:
DEBUG NHibernate.SQL (null) - INSERT INTO Profile_Queue_Telephone (ProfileId, QueueId, TelephoneId) VALUES (?p0, ?p1, ?p2);?p0 = 7283 [Type: Int32 (0:0:0)], ?p1 = 27434 [Type: Int32 (0:0:0)], ?p2 = 26749 [Type: Int32 (0:0:0)]
DEBUG NHibernate.SQL (null) - SELECT LAST_INSERT_ID()
DEBUG NHibernate.SQL (null) - SELECT this_.Id as id1_45_0_, this_.ProfileId as profileid2_45_0_, this_.QueueId as queueid3_45_0_, this_.TelephoneId as telephone4_45_0_ FROM Profile_Queue_Telephone this_ WHERE this_.Id = ?p0;?p0 = 74 [Type: Int32 (0:0:0)]
I'm puzzled as to why this is not executed on the database, as NHibernate clearly stores it in some kind of cache, since I'm able to retrieve the data. And if it was because of a rollback, I'm assuming that would have been stated in the log, that a rollback happened on the MySql server.
So my question is what I'm missing here, what do I do to get the object inserted into the database?
Edit:
It might be worth noting that I'm very new to NHibernate. I'm working on a 4+ year old project, written with NHibernate.
Your wrapper method session.Begin()
starts a transaction but you never call the corresponding Commit
to permanently save the changes to the database. Without that, the changes will be rolled back and your database effectively untouched. One of your wrapper methods should be calling _transaction.Commit
, find that method and call it.