本文剖析一個 iBatis.NET 三層架構 Demo,涵蓋專案結構、核心組態檔、SQL Map 撰寫、業務層封裝,並深入探討 iBatis.NET 的適用場景與不適用場景。
<param name="File" value="../Log/log.txt"/>)| 檔案 | 用途 |
|---|---|
sqlmap.config | 核心組態:properties、provider、database、sqlMaps 設定 |
database.config | 資料庫連線字串,被 sqlmap.config 的 <properties embedded="database.config,Service.SqlMaps"/> 參考 |
providers.config | iBatis 內建 provider 設定,通常無需修改 |
MapSqlClientPerson.xml | SQL Map 檔:支援存儲程序、內嵌 SQL、動態 SQL、ORM 映射 |
CodeMyBatis.cs | 初始化 ISqlMapper 的工具類,擴充支援 DataTable/DataSet 輸出 |
Script | 建表與測試資料 SQL 腳本 |
<select id="SelectAllPerson2" resultMap="SelectAllResult">
select PER_ID AS Id, PER_FIRST_NAME AS FirstName, ...
from PERSON
<dynamic prepend="WHERE">
<isParameterPresent>
PER_FIRST_NAME LIKE #FirstName#+'%'
</isParameterPresent>
</dynamic>
</select>
關鍵提示:輸出為 DataTable/DataSet 時,resultMap 不生效,SQL 必須用 AS 別名對應實體屬性名稱。建議實體屬性與資料庫欄位命名一致,減少映射設定。
// 基底類別,提供 SqlMapper 存取
public class IBll
{
protected static ISqlMapper SqlMap = MyBatis.SqlMap;
}
// 業務服務類別
public class PersonService : IBll
{
public IList<Person> GetAllPerson()
=> SqlMap.QueryForList<Person>("SelectAllPerson", null);
public DataTable GetAllPerson2()
{
int recCount = 0;
return MyBatis.QueryForDataTable("SelectAllPerson2",
new Person { FirstName = "kilo" }, 10, 1, out recCount);
}
}
運行環境:VS2008 + SQL Server 2000/2005。原始碼經升級精簡,感謝原作者貢獻。