用template是hibernate推荐的执行方式。I
AdoTemplate 执行sql核心代码:
public virtual object Execute(IDataAdapterCallback dataAdapterCallback)
{
ConnectionTxPair connectionTxPairToUse = GetConnectionTxPair(DbProvider);
IDbDataAdapter dataAdapter = null;
try
{
dataAdapter = DbProvider.CreateDataAdapter();
//TODO row updated event handling...
dataAdapter.SelectCommand = DbProvider.CreateCommand();
dataAdapter.SelectCommand.Connection = connectionTxPairToUse.Connection;
//TODO register for warnings on connection.
dataAdapter.SelectCommand.Transaction = connectionTxPairToUse.Transaction;
ApplyCommandSettings(dataAdapter.SelectCommand);
object result = dataAdapterCallback.DoInDataAdapter(dataAdapter);
return result;
}
catch (Exception)
{
DisposeDataAdapterCommands(dataAdapter);
//TODO set dataAdapter command's = null; ?
//TODO exception translation? different hierarchy for data set operations.
DisposeConnection(connectionTxPairToUse.Connection, DbProvider);
connectionTxPairToUse.Connection = null;
throw;
}
finally
{
DisposeDataAdapterCommands(dataAdapter);
DisposeConnection(connectionTxPairToUse.Connection, DbProvider);
}
}
HibernateTemplate 执行sql核心代码:
public object Execute(IHibernateCallback action, bool exposeNativeSession)
{
ISession session = Session;
bool existingTransaction = SessionFactoryUtils.IsSessionTransactional(session, SessionFactory);
if (existingTransaction)
{
if(log.IsDebugEnabled) log.Debug("Found thread-bound Session for HibernateTemplate");
}
FlushModeHolder previousFlushModeHolder = new FlushModeHolder();
try
{
previousFlushModeHolder = ApplyFlushMode(session, existingTransaction);
ISession sessionToExpose = (exposeNativeSession ? session : CreateSessionProxy(session));
Object result = action.DoInHibernate(sessionToExpose);
FlushIfNecessary(session, existingTransaction);
return result;
}
catch (ADOException ex)
{
IDbProvider dbProvider = SessionFactoryUtils.GetDbProvider(SessionFactory);
if (dbProvider != null && dbProvider.IsDataAccessException(ex.InnerException))
{
throw ConvertAdoAccessException(ex);
}
else
{
throw new HibernateSystemException(ex);
}
}
catch (HibernateException ex)
{
throw ConvertHibernateAccessException(ex);
}
catch (Exception ex)
{
IDbProvider dbProvider = SessionFactoryUtils.GetDbProvider(SessionFactory);
if (dbProvider != null && dbProvider.IsDataAccessException(ex))
{
throw ConvertAdoAccessException(ex);
}
else
{
// Callback code throw application exception or other non DB related exception.
throw;
}
}
finally
{
if (existingTransaction)
{
if (log.IsDebugEnabled) log.Debug("Not closing pre-bound Hibernate Session after HibernateTemplate");
if (previousFlushModeHolder.ModeWasSet)
{
session.FlushMode = previousFlushModeHolder.Mode;
}
}
else
{
// Never use deferred close for an explicitly new Session.
if (AlwaysUseNewSession)
{
SessionFactoryUtils.CloseSession(session);
}
else
{