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

NHibernate 多表查詢兩大解決方案:臨時表 vs 自訂實體類

     編輯:關於.NET

背景與挑戰

在使用 NHibernate 開發專案時,多表聯查是常見需求。本文整理兩種主流解決方案,並比較優缺點。

方案一:HQL 查詢 + DataTable 臨時表

步驟 1:撰寫 HQL 聯查語句

string sql = "select oo.Orgid, go.Orgname " +
             "from JkptOaxtOrganization as oo, JkptGlxtOrganization as go " +
             "where oo.Orgid = " + orgid + " and oo.Suborgid = go.Orgid";
IQuery query = session.CreateQuery(sql);
IList list = query.List();

若映射檔已設定關聯,可省略 where 條件。

步驟 2:手動建立 DataTable 填入資料

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Orgid", typeof(int)));
dt.Columns.Add(new DataColumn("Orgname", typeof(string)));

foreach (object[] row in list)
{
    DataRow dr = dt.NewRow();
    dr["Orgid"] = row[0];
    dr["Orgname"] = row[1];
    dt.Rows.Add(dr);
}
ds.Tables.Add(dt);

缺點分析

  • 欄位多時手寫 DataColumn 極其繁瑣(50 欄位需 50 行程式碼)。
  • 用畢須手動清理臨時表,易造成資源洩漏。
  • 型別轉換需自行處理,維護成本高。

方案二:select new 自訂實體類(推薦)

步驟 1:HQL 直接投影到自訂類別

string sql = "select new OaxtJoinGlxt(oo.Orgid, gg.Orgname) " +
             "from JkptOaxtOrganization as oo, JkptGlxtOrganization as gg " +
             "where oo.Orgid = " + orgid + " and oo.Suborgid = gg.Orgid";
IList list = session.CreateQuery(sql).List();

步驟 2:定義輕量級 DTO 類別

public class OaxtJoinGlxt
{
    public OaxtJoinGlxt(decimal pOrgid, string pOrgname)
    {
        _Orgid = pOrgid;
        _Orgname = pOrgname;
    }

    private decimal? _Orgid;
    public decimal? Orgid { get => _Orgid; set => _Orgid = value; }

    private string _Orgname;
    public string Orgname { get => _Orgname; set => _Orgname = value; }
}

步驟 3:在 .hbm.xml 註冊匯入

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <import class="Model.OaxtJoinGlxt,Model"/>
  <class name="Model.JkptGlxtOrganization,Model" table="JKPT_GLXT_ORGANIZATION" lazy="false">
  ...
</hibernate-mapping>

方案比較總結

項目臨時表方案自訂實體方案
程式碼量大(需手寫欄位)小(僅建構子對應)
型別安全弱(object[] 需轉型)強(強型別屬性)
維護性差佳
效能略低(多次複製)較高(直接投影)

結論: 除非極簡單的臨時需求,否則強烈建議採用「select new + 自訂 DTO」方案,開發效率與執行效能雙贏。

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