iBatis.Net 是一個輕量級的 ORM 框架,它允許開發者通過直接編寫 SQL 查詢來操作數據庫,并將查詢結果映射到對象模型中。與其他 ORM 框架相比,iBatis.Net 提供了更大的 SQL 靈活性,同時保留了與數據庫的緊密控制。本文將通過實際的代碼示例,詳細介紹如何在 .NET 環境中使用 iBatis.Net 進行數據庫操作。
一、iBatis.Net 基本配置
要使用 iBatis.Net 進行數據庫操作,首先需要進行基本的配置,包括數據庫連接配置和 SQL 映射文件的編寫。
1. 配置數據庫連接
創建一個名為 SqlMap.config 的文件,用于配置數據庫連接信息。
<?xml version="1.0" encoding="utf-8" ?>
<sqlMapConfig xmlns="//ibatis.apache.org/dataMapper">
<database>
<provider type="System.Data.SqlClient"/>
<dataSource connectionString="Data Source=YourServer;Initial Catalog=YourDatabase;Integrated Security=True;" />
</database>
</sqlMapConfig>
2. 定義 SQL 映射文件
接下來,創建 SQL 映射文件 User.xml,用于定義與 User 表相關的 SQL 操作。
<?xml version="1.0" encoding="utf-8" ?>
<sqlMap namespace="User" xmlns="//ibatis.apache.org/dataMapper">
<select id="GetUserById" parameterClass="int" resultClass="User">
SELECT Id, Name, Age FROM Users WHERE Id = #value#
</select>
<insert id="InsertUser" parameterClass="User">
INSERT INTO Users (Name, Age) VALUES (#Name#, #Age#)
</insert>
<update id="UpdateUser" parameterClass="User">
UPDATE Users SET Name = #Name#, Age = #Age# WHERE Id = #Id#
</update>
<delete id="DeleteUser" parameterClass="int">
DELETE FROM Users WHERE Id = #value#
</delete>
</sqlMap>
二、BaseDAL 工具類的設計與實現
為了簡化數據庫操作,我們可以通過一個工具類來封裝常用的數據庫操作方法。以下是一個基于 iBatis.Net 的 BaseDAL 類的實現,提供了增、刪、改、查等常見的數據庫操作方法。
using IBatisNet.DataMapper;
using IBatisNet.DataMapper.MappedStatements;
using IBatisNet.DataMapper.Scope;
using IBatisNet.DataMapper.SessionStore;
using log4net;
using System;
using System.Collections.Generic;
namespace CarRental.DAL
{
public enum IBatisActionType
{
Insert = 0,
Update,
Delete
}
public class ActionItem
{
public string IBatisSqlIdName { get; set; }
public object DataObj { get; set; }
}
public class BaseDAL
{
static ILog log = LogManager.GetLogger(typeof(BaseDAL));
public static void InitSqlMapper()
{
ISqlMapper iSqlMapper = Mapper.Instance();
if (iSqlMapper != null)
{
iSqlMapper.SessionStore = new HybridWebThreadSessionStore(iSqlMapper.Id);
}
}
public static ISqlMapper GetSqlMapper()
{
return Mapper.Instance();
}
public static int Insert<T>(string statementName, T t)
{
ISqlMapper iSqlMapper = Mapper.Instance();
if (iSqlMapper != null)
{
return (int)iSqlMapper.Insert(statementName, t);
}
return 0;
}
public static int Update<T>(string statementName, T t)
{
ISqlMapper iSqlMapper = Mapper.Instance();
if (iSqlMapper != null)
{
return iSqlMapper.Update(statementName, t);
}
return 0;
}
public static int Delete(string statementName, int primaryKeyId)
{
ISqlMapper iSqlMapper = Mapper.Instance();
if (iSqlMapper != null)
{
return iSqlMapper.Delete(statementName, primaryKeyId);
}
return 0;
}
public static T Get<T>(string statementName, int primaryKeyId) where T : class
{
ISqlMapper iSqlMapper = Mapper.Instance();
if (iSqlMapper != null)
{
return iSqlMapper.QueryForObject<T>(statementName, primaryKeyId);
}
return null;
}
public static IList<T> QueryForList<T>(string statementName, object parameterObject = null)
{
ISqlMapper iSqlMapper = Mapper.Instance();
if (iSqlMapper != null)
{
return iSqlMapper.QueryForList<T>(statementName, parameterObject);
}
return null;
}
// 更多封裝方法...
}
}
三、BaseDAL 工具類的使用示例
通過封裝好的 BaseDAL 類,可以非常方便地進行數據庫操作,下面是如何調用這些方法的示例。
1. 插入數據
User newUser = new User { Name = "John Doe", Age = 30 };
int newUserId = BaseDAL.Insert("InsertUser", newUser);
2. 更新數據
User existingUser = BaseDAL.Get<User>("GetUserById", userId);
existingUser.Name = "Jane Doe";
BaseDAL.Update("UpdateUser", existingUser);
3. 刪除數據
int result = BaseDAL.Delete("DeleteUser", userId);
4. 查詢數據
User user = BaseDAL.Get<User>("GetUserById", userId);
IList<User> users = BaseDAL.QueryForList<User>("GetAllUsers");
四、事務操作
iBatis.Net 還支持事務操作,可以確保一組數據庫操作要么全部成功,要么全部失敗。BaseDAL 類提供了 DoActionWithTransaction 方法,可以在事務中執行一系列數據庫操作。
以下是一個使用 BaseDAL 類進行事務操作的完整示例。在這個示例中,首先插入一條新的汽車類型數據,然后使用新插入的汽車類型 ID 繼續插入一條對應的價格規則數據。整個操作被包裹在一個事務中,以確保數據一致性。
try
{
// 開始事務
BaseDAL.GetSqlMapper().BeginTransaction();
// 創建一個新的汽車類型對象
var carType = new
{
name = "SUV",
description = "Sport Utility Vehicle"
};
// 插入新的汽車類型數據,并獲取新記錄的ID
int carTypeId = BaseDAL.Insert("InserNewCarTypeIntoTCar", carType);
// 創建一個價格規則對象,并將新插入的汽車類型ID賦值給它
var priceRule = new
{
car_type_id = carTypeId,
base_price = 500,
per_km_price = 10
};
// 插入價格規則
BaseDAL.InsertWithNoResult("InserNewCarTypeIntoTPriceRule", priceRule);
// 提交事務
BaseDAL.GetSqlMapper().CommitTransaction();
Console.WriteLine("事務提交成功,汽車類型和價格規則已插入數據庫。");
}
catch (Exception ex)
{
// 如果發生錯誤,回滾事務
BaseDAL.GetSqlMapper().RollBackTransaction();
Console.WriteLine("事務回滾,操作未完成。錯誤信息: " + ex.Message);
}
五、iBatis.Net操作總結
iBatis.Net 是一個輕量級且靈活的 ORM 框架,特別適用于需要直接控制 SQL 語句的場景。通過本文的介紹,iBatis.Net 的基本配置、常用數據庫操作,以及事務管理等內容得到了詳細的展示。結合使用 BaseDAL 類,開發者可以有效地簡化與數據庫交互的代碼,同時保持對 SQL 操作的完全控制。iBatis.Net 提供了更高的 SQL 靈活性,能夠在需要復雜查詢和自定義 SQL 的項目中發揮重要作用。
iBatis.Net 在常用 ORM 框架中具有非常突出的表現,以下是 iBatis.Net 與其他流行的 ORM 框架的對比:
| 特性 | iBatis.Net | Entity Framework | Dapper | NHibernate |
|---|---|---|---|---|
| SQL 靈活性 | 高 | 中等 | 高 | 中等 |
| 自動化 | 低 | 高 | 低 | 高 |
| 學習曲線 | 中等 | 高 | 低 | 高 |
| 性能 | 高 | 中等 | 高 | 中等 |
| 事務支持 | 支持 | 支持 | 支持 | 支持 |
| 映射能力 | 中等 | 豐富 | 基本 | 豐富 |
| 適用場景 | 復雜 SQL 查詢 | 快速開發和強類型支持 | 高性能需求和簡單映射 | 企業級復雜應用 |
通過對比可以看出,iBatis.Net 在處理復雜 SQL 查詢和需要精確控制數據庫操作的場景下具有顯著優勢,而在自動化和易用性方面,其他框架如 Entity Framework 和 NHibernate 可能更適合快速開發需求。這些差異使得 iBatis.Net 成為一種在特定項目中不可替代的工具,特別是在靈活性和性能需求較高的環境中。