我正在使用Castle Active Record和NHibernate,并且需要能够在不使用会话的情况下运行HQL更新。当我使用会话时,它最终导致锁定问题:
public static ISession GetSession(out ISessionFactoryHolder factoryHolder, out bool created)
{
created = false;
var type = typeof(T);
factoryHolder = ActiveRecordMediator.GetSessionFactoryHolder();
ISessionScope activeScope = factoryHolder.ThreadScopeInfo.GetRegisteredScope();
ISession session = null;
var key = factoryHolder.GetSessionFactory(type);
if (activeScope == null)
{
created = true;
session = factoryHolder.CreateSession(type);
}
else
{
if (activeScope.IsKeyKnown(key))
session = activeScope.GetSession(key);
else
session = factoryHolder.GetSessionFactory(type).OpenSession();
}
return session;
}
public static void UpdateQuery(string query)
{
ISessionFactoryHolder factoryHolder;
var created = false;
var session = GetSession(out factoryHolder, out created);
session.CreateQuery(query).ExecuteUpdate();
if (created)
factoryHolder.ReleaseSession(session);
}
由于会话中发生的所有锁定,这在我们的生产环境中造成了重大问题。如何在不实例化会话的情况下运行hql更新?
答案 0 :(得分:0)
您无法在NHibernate会话之外执行HQL。但是,您可能会发现使用无状态会话将有所帮助(在ActiveRecord中使用StatelessSessionScope)。
或者,如果无状态会话仍然不够高,则必须使用简单的SQL执行查询,使用session.CreateSqlQuery(...)