首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

NHibernate實戰(6):事務管理模式與代碼覆蓋率實戰

     編輯:關於.NET

前言

任何數據操作都應包裹在事務中,即使是查詢。本文建立標準事務模板,並演示使用 TestDriven.NET + NCover 進行代碼覆蓋率分析的實戰技巧。

NHibernate 事務核心模式

using (ITransaction tx = _session.BeginTransaction())
{
    try
    {
        // CRUD 操作
        tx.Commit();
    }
    catch (HibernateException)
    {
        tx.Rollback();
        throw;
    }
}

關鍵點:

  • using 確保事務資源釋放
  • try-catch 捕獲異常執行回滾
  • _session.Flush() 同步內存狀態到資料庫(Commit 前自動觸發,顯式調用可提前發現錯誤)
  • 讀操作同樣需事務:保證隔離級別、延遲加載可用、異常時一致性

四大操作事務封裝

1. 新建對象

public int CreateCustomerTransaction(Customer customer)
{
    using (ITransaction tx = _session.BeginTransaction())
    {
        try
        {
            int newId = (int)_session.Save(customer);
            _session.Flush();
            tx.Commit();
            return newId;
        }
        catch (HibernateException)
        {
            tx.Rollback();
            throw;
        }
    }
}

2. 刪除對象

public void DeleteCustomerTransaction(Customer customer)
{
    using (ITransaction tx = _session.BeginTransaction())
    {
        try
        {
            _session.Delete(customer);
            _session.Flush();
            tx.Commit();
        }
        catch (HibernateException)
        {
            tx.Rollback();
            throw;
        }
    }
}

3. 更新對象

public void UpdateCustomerTransaction(Customer customer)
{
    using (ITransaction tx = _session.BeginTransaction())
    {
        try
        {
            _session.Update(customer);
            _session.Flush();
            tx.Commit();
        }
        catch (HibernateException)
        {
            tx.Rollback();
            throw;
        }
    }
}

4. 批量保存/更新

public void SaveOrUpdateCustomersTransaction(IList<Customer> customers)
{
    using (ITransaction tx = _session.BeginTransaction())
    {
        try
        {
            foreach (Customer c in customers)
                _session.SaveOrUpdate(c);
            _session.Flush();
            tx.Commit();
        }
        catch (HibernateException)
        {
            tx.Rollback();
            throw;
        }
    }
}

代碼覆蓋率實戰:NCover 分析

測試場景一:成功提交

[Test]
public void CreateCustomerTransactionTest()
{
    var customer = new Customer { Firstname = "YJing", Lastname = "Lee" };
    int newIdentity = _transaction.CreateCustomerTransaction(customer);
    var testCustomer = _transaction.GetCustomerById(newIdentity);
    Assert.IsNotNull(testCustomer);
}
  • 操作:右鍵測試方法 → "Test With" → "Coverage"
  • NCoverExplorer 顯示 CreateCustomerTransaction 方法 100% 覆蓋,執行路徑:Save → Flush → Commit → Return

測試場景二:異常回滾

[Test]
[ExpectedException(typeof(HibernateException))]
public void CreateCustomerThrowExceptionOnFailTest()
{
    var customer = new Customer
    {
        Firstname = "012345678901234567890123456789012345678901234567890123456789", // 超長觸發截斷錯誤
        Lastname = "YJingLee"
    };
    _transaction.CreateCustomerTransaction(customer);
}
  • 覆蓋率分析顯示異常路徑:Catch → Rollback → Throw
  • 驗證事務確實回滾,資料庫無髒數據

最佳實踐總結

場景事務必要性關鍵操作
單條寫入必須Save + Flush + Commit
批量寫入必須循環 SaveOrUpdate + Flush + Commit
查詢/延遲加載必須保證 Session 開啟、隔離級別
跨多個 DAO 方法必須上層協調事務邊界(Service 層)

結語

事務是數據一致性基石,NHibernate 強制事務設計體現嚴謹工程觀。結合 NCover 覆蓋率分析,可量化驗證正常與異常路徑完整覆蓋。下篇將深入並發控制機制。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved