在實務開發中,常遇到只需更新資料表單一欄位的情境(例如:將「是否瀏覽」標記設為 1)。NHibernate 提供 ISQLQuery.ExecuteUpdate() 方法,可直接執行 Native SQL 達到高效更新,避免載入完整實體物件的開銷。
public static bool UpdateIsBrowse(decimal id)
{
bool isSuccess = false;
ITransaction trans = session.BeginTransaction();
try
{
// 直接執行 UPDATE 陳述式
string sql = "UPDATE jkpt_oaxt_weatherforecast SET Isbrowse = 1 WHERE Weatherforecastid = " + id;
ISQLQuery query = session.CreateSQLQuery(sql).AddEntity(typeof(JkptOaxtWeatherforecast));
query.ExecuteUpdate();
session.Flush();
trans.Commit();
Helpers.SaveInfo("Update weatherforecast 's isbrowse Success!");
isSuccess = true;
}
catch (Exception ex)
{
isSuccess = false;
trans.Rollback();
Helpers.SaveInfo("更新是否瀏覽失敗!錯誤提示:" + ex.Message);
}
finally
{
if (session != null) session.Clear();
}
return isSuccess;
}
finally 區塊呼叫 session.Clear() 清理一級快取,避免記憶體洩漏。:id)防止 SQL 注入,範例為簡化示範採用字串串接。此模式適用於無商業邏輯驗證、無級聯更新、單純旗標更新的情境。若涉及複雜業務規則、驗證或需觸發事件,仍建議使用標準 NHibernate 實體更新流程(session.Update(entity))以保持領域模型完整性。