IBatis.net介绍
IBatis.net介紹
IBatis.net 是2001年發起的開源項目,它是一個輕量級的ORM框架,現在IBatisNET已經是屬于Apache下的一個子項目了,最新版本是1.6.2.
官方網站:http://www.mybatis.org/
.net項目下載地址:http://code.google.com/p/mybatisnet/
DataMapper:通過配置映射關系的xml業務對象與SQL語句和存儲過程進行映射.
DataAcces:簡單的說就是IBatis的數據訪問層.
?
IBatis.net配置
主要要用到的幾個配置文件:
providers.config 這個直接拷貝到根目錄,該文件定義各種數據庫的驅動,包括SqlServer, Oracle, MySQL, PostgreSQL, DB2 and OLEDB, ODBC 等。
sqlmap.config 就是非常核心的一個配置文件,主要配置了數據庫訪問字符串,settings設置,以及配置實體類和數據庫表相關xml。
還有一個database.config 文件,它是配置一些在sqlmap中用到得參數.
然后需要引入兩個DLL文件.
sqlmap.config文件代碼:
<?xml version="1.0" encoding="utf-8"?> <sqlMapConfig xmlns="http://ibatis.apache.org/dataMapper" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> ? <!--<providers resource="database.config" />--> <settings> <setting useStatementNamespaces="true"/> <setting cacheModelsEnabled="true"/> </settings> ? <providers resource="providers.config" /> <database> <!-- Optional ( default ) --> <provider name="sqlServer2.0"/> <dataSource name="iBatisNet" connectionString="Server=.; User ID=sa;Password=sa;Database=TestDB;Persist Security Info=True"/> </database> <sqlMaps> <sqlMap resource="Maps/Account.xml"/> </sqlMaps> </sqlMapConfig>useStatementNamespaces:是否啟用命名空間
cacheModelsEnabled:是否緩存數據
? <providers resource="providers.config" /> 引入數據庫驅動文件
sqlMaps 節點就是配置一些sql語句以及實體映射的xml文件.
?
IBatis.net實戰
現在讓我們來做一個Demo
我用的是Sqlserver2005 ,新建一個數據表
在Vs2010下新建項目IBatisDemo
項目結構如下
IBatisDemo.Dao 提供一個統一的Mapper訪問接口,
IBatisDemo.Model 數據實體
IBatisDemo.Service 數據操作
因為是做Demo沒有對整體架構做過多的細節設置.
首先配置網站根目錄下的Maps/Account.xml如下:
<?xml version="1.0" encoding="utf-8" ?> <sqlMap namespace="Account" xmlns="http://ibatis.apache.org/mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <alias> <!-- alias:取別名 assembly:表示類所在的文件 type:表示該類的完整的名稱 --> <typeAlias alias="Account" assembly="IBatisDemo.Model.dll" type="IBatisDemo.Model.Accounts" /> </alias> ? <resultMaps> <resultMap id="Account-result" class="Account"> <result property="Id" column="id"/> <result property="Item" column="Item"/> <result property="Year" column="Year"/> <result property="Month" column="Month"/> <result property="Day" column="Day"/> <result property="CreateOn" column="CreateOn"/> <result property="Level" column="Level"/> </resultMap> </resultMaps> ? <statements> <select id="sql_selectByid" resultMap="Account-result"> select * from Accounts <dynamic prepend="where"> <isParameterPresent property="id" prepend=""> [id] = #id# </isParameterPresent> </dynamic> </select> ? <select id="sql_selectAll" resultMap="Account-result"> select * from Accounts </select> ? <insert id="sql_InsertOne" parameterClass="Account"> insert into Accounts (Item,Money,Year,Month,Day,CreateOn,Level) values (#Item#, #Money#, #Year#, #Month#, #Day#, #CreateOn#, #Level# ) <selectKey type="post" resultClass="int" property="Id"> SELECT CAST(@@IDENTITY as int) as Id </selectKey> </insert> </statements> </sqlMap>說明:
statements 節點:
在這些容器標簽中有一些常用的屬性如下所示
resultMap和resultclass對比:
1、resultMap屬于直接映射,可以把結果集中的數據庫字段與實體類中的屬性一一對應,這樣通過select語句得到的結果就會準確的對上號
2、resultclass屬于隱身映射,雖然你指定resultclass=“”,具體某一個類,但是select語句得到的結果是一條實力記錄,但如果數據庫字段與類的屬性名字不一致,這個時候就會出現映射錯誤,有一種方式可以解決就是在寫select語句時,給每個字段用as運算符取名字與屬性一樣:例如:select realname as name...其中realname是字段列名,name是屬性字段名
3、resultmap比resultclass性能要高。盡量使用resultmap
insert標簽下的selectKey? 是表示返回剛插入數據的主鍵id,具體說明如下
<!-- 為了使insert操作能夠返回插入記錄的id,必須為insert寫一個selectKey –> <!-- 下面是sqlserver寫法--> <selectKey type="post" resultClass="int" property="Id"> SELECT CAST(@@IDENTITY as int) as Id </selectKey> <!-- 下面是針對Oracle的寫法,Oracle沒有autoincrement,而是用觸發器實現的 CURRVAL是在觸發器中定義的 --> <!--<insert id="insertRemark" parameterClass="RemarkInfo"> insert into SGS_REMARK(REMARK) values(#remark#) <selectKey resultClass="int" keyProperty="id" > SELECT S_SGS_REMARK.CURRVAL AS ID FROM DUAL </selectKey> </insert> --> <!-- 下面是針對MySQL的寫法 --> <!-- <selectKey resultClass="int" keyProperty="id" > SELECT @@IDENTITY AS id </selectKey> --> ?Account.xml配置完成 .建實體類:
using System; using System.Collections.Generic; ? using System.Text; ? namespace IBatisDemo.Model { public class Accounts { public int Id { get; set; } ? public string Item { get; set; } ? public float Money { get; set; } ? public int Month { get; set; } ? public int Year { get; set; } ? public int Day { get; set; } ? public DateTime CreateOn { get; set; } ? public string Level { get; set; } } }Mapper.cs 獲取Mapper的對象類:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using IBatisNet.DataMapper; using IBatisNet.Common.Utilities; using IBatisNet.DataMapper.Configuration; ? namespace IBatisDemo.Dao { public class Mapper { 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(handler); } ? public static ISqlMapper Instance() { if (_mapper == null) { lock (typeof(SqlMapper)) { if (_mapper == null) // double-check { InitMapper(); } } } return _mapper; } ? public static ISqlMapper Get() { return Instance(); } ? ? /// <summary> /// RealMarket Mapper /// </summary> public static ISqlMapper GetMaper { get { if (_mapper == null) { lock (typeof(ISqlMapper)) { if (_mapper == null) { ConfigureHandler hander = new ConfigureHandler(Configure); DomSqlMapBuilder builder = new DomSqlMapBuilder(); _mapper = builder.ConfigureAndWatch("sqlmap.config", hander); } } } return _mapper; } } } }然后再Service里面建立AccountService.cs 數據訪問
using System; using System.Collections.Generic; ? using System.Text; using System.Reflection; using System.IO; using IBatisDemo.Model; using System.Data.SqlClient; using IBatisDemo.Dao; ? namespace IBatisDemo.Service { public class AccountService { public int TestInsertOne(Accounts account) { Object obj =Mapper.GetMaper.Insert("Account.sql_InsertOne", account); return (int)obj; } ? public Accounts GetAccount(int id) { return (Accounts)Mapper.GetMaper.QueryForObject("Account.sql_selectByid", id); } ? public IList<Accounts> GetAccountList() { return Mapper.GetMaper.QueryForList<Accounts>("Account.sql_selectAll", null); } } }這里要注意命名空間.
在Default.aspx頁面上調用Service
protected void Button1_Click(object sender, EventArgs e) { Accounts account = new Accounts(); account.Id =-1; account.CreateOn = DateTime.Now; account.Day = 12; account.Item = "小剛1"; account.Level = "無"; account.Money = 56; account.Month = 6; account.Year = 2011; ? AccountService service = new AccountService(); service.TestInsertOne(account); } ? protected void Button3_Click(object sender, EventArgs e) { AccountService service = new AccountService(); IList<Accounts> accounts = service.GetAccountList(); ? this.GridView1.DataSource = accounts; this.GridView1.DataBind(); } ? protected void Button2_Click(object sender, EventArgs e) { AccountService service = new AccountService(); Accounts account = service.GetAccount(2); }運行效果:
總結
以上是生活随笔為你收集整理的IBatis.net介绍的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 解决 Windows Update 时提
- 下一篇: 不问苍生问鬼神(说一说不问苍生问鬼神的简