查看文章索引請通過http://www.cnblogs.com/seesea125/archive/2012/04/17/2453256.html
IBatis.net官方下載地址:http://www.mybatis.org/
IBatis.net作用是把數據庫查詢與對象的屬性間建立映射關系。但它並不是一個實體關系映射工具,僅用於幫助程序人員建立實體和SQL語句或者存儲過程間的映射。因此只能叫半自動OR/M工具。
IBatis.net的配置:
一、引用幾個DLL,注意在數據層引用即可。
單獨使用映射的情況下,只需要引用IBatisNet.DataMapper.dll就可以了
其中IBatisNet.Common.dll和Castle.DynamicProxy.dll是必須的
COMMON是我自己的,不用管它
IBatisNet.DataAccess.dll是可選的,如果使用Data Access組件,則還需要添加對IBatisNet.DataAccess.dll的引用。
二、完成對組件的添加后,還需要添加三個XML文檔
1 providers.config ----DataMapper根據這個確定是什么類型數據庫(放在數據層)
2 SqlMap.xml ----數據映射文檔,里面包含了SQL語句(放在數據層)
3 SqlMap.config ----DataMapper的配置文檔,它詳細描述了工程中SqlMap.XML和providers.config文檔的位置,以及其他配置項(必須放在Web跟目錄下)。
先看SqlMap.config
< sqlMapConfig xmlns ="http://ibatis.apache.org/dataMapper" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" > < settings >
< setting useStatementNamespaces ="true" />//如果是true,那么寫數據查詢時,查詢語句的名稱前要添加它的完整命名空間
< setting cacheModelsEnabled ="true" />//全局化配置DataMapper客戶能否啟用cache,默認是true
</ settings >
< providers embedded ="DAL.providers.config, DAL" /> //指定providers.config的位置
< database >
< provider name ="sqlServer2.0" /> //如果使用默認的數據提供者,這句可以不要,如果系統中使用多個數據庫,需要配置provider的內容
< dataSource name ="ConnStr" connectionString ="Data Source=.;Database=Test;User ID=sa;Password=123456;Connection Lifetime=3;Min Pool Size=1;Max Pool Size=50;MultipleActiveResultSets=true;" /> //數據庫鏈接字符串,
</ database >
< sqlMaps >
< sqlMap embedded ="DAL.Maps.UserInfo.xml, DAL" /> //程序的數據映射文件的位置,如果有多個XML,就寫多行,如果比較多,也可以當一個單獨的XML中去寫,比如 < sqlMap resource =”Maps/All.XML”/>,然后在ALL.xml再添加數據映射文件,這樣就實現了加載一組數據映射文件
</sqlMaps >
</ sqlMapConfig >
具體文檔配置可在附件的DEMO中下載查看。
三、創建SqlMapper實例,這個是單例模式,文件名SqlMapper.CS,放在數據層中。
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IBatisNet.Common.Utilities;
using IBatisNet.DataMapper;
using IBatisNet.DataMapper.Configuration;
using IBatisNet.DataMapper.SessionStore;
namespace DAL
{
public class SqlMapper
{
private static volatile ISqlMapper _mapper = null;
protected static void Configure( object obj)
{
_mapper = null;
}
protected static void InitMapper()
{
ConfigureHandler handler = new ConfigureHandler(Configure);
DomSqlMapBuilder builder = new DomSqlMapBuilder();
_mapper = builder.ConfigureAndWatch( " SqlMap.config ", handler);
_mapper.SessionStore = new HybridWebThreadSessionStore(_mapper.Id);
}
public static ISqlMapper Instance()
{
if (_mapper == null)
{
lock ( typeof(SqlMapper))
{
if (_mapper == null) // double-check
{
InitMapper();
}
}
}
return _mapper;
}
public static ISqlMapper Get()
{
return Instance();
}
}
}
外界調用方法:
IList list = SqlMapper.Instance().QueryForObject<list>("UserInfo.GetCount", param);
因為是單例的,第一次調用時,DomSqlMapBuilder對象會通過查詢SqlMap.config來創建一個sqlMapper實例,以后調用就直接從緩存讀取了。
DomSqlMapBuilder.ConfigureAndWatch()方法負責監視配置文件的更新情況,如果配置或者映射文件有更新,SqlMapper對象會重新載入並不重啟系統
整個配置已經結束,具體可參考DEMO:DEMO下載