IBatis.net在asp.net MVC下的使用


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的配置和使用

一、首先需要下載Ibatis.net 的dll.上面的官網估計下載不下來,所以這兒我自己上傳了一份

下載地址:

IBatis.net1.9.2&1.6.2最新版本 

本項目的 Demo:

asp.net MVC和IBatis.net整合demo程序

本項目的數據庫:

asp.net MVC和IBatis.net整合demo數據庫部分

 

二、使用VS 2013新建一個解決方案。

首先使用sqlserver2014 建立數據庫表

數據庫:UserDemoDb

並建立相關的架構  如圖所示

 

IBatisDemo.Dao 提供一個統一的Mapper訪問接口,

IBatisDemo.Model 數據實體

IBatisDemo.Service 數據操作

因為是做Demo沒有對整體架構做過多的細節設置.

 

三、IBatis.net配置

web層拷貝的配置文件,這些文件在 Ibatis.net1.9.2的程序中 解壓就有

providers.config 這個直接拷貝到根目錄,該文件定義各種數據庫的驅動,包括SqlServer, Oracle, MySQL, PostgreSQL, DB2 and OLEDB, ODBC 等。

sqlmap.config 就是非常核心的一個配置文件,主要配置了數據庫訪問字符串,settings設置,以及配置實體類和數據庫表相關xml。

還有一個database.config 文件,它是配置一些在sqlmap中用到得參數.

添加對Ibatis 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">
  <settings>
    <!--啟用命名空間,對於多個表的時候,進行區分-->
    <setting useStatementNamespaces="true"/>
  </settings>
  <!--連接數據庫驅動文件-->
  <providers resource="providers.config"/>

	<!-- Database connection information -->
  <database>
    <!--配置數據庫連接字符串-->
    <provider name="sqlServer2.0"></provider>
    <dataSource name="IBatisNet" connectionString="server=WWW;database=UserDemoDb;user id=sa;password=DDD;connection reset=false;"/>
  </database>
  <sqlMaps>
    <!--引用數據庫表實體xml文件-->
    <sqlMap resource="Maps/UserInfo.xml" />
  </sqlMaps>

</sqlMapConfig>

  

先配置網站根目錄下的Maps/UserInfo.xml如下:

<?xml version="1.0" encoding="utf-8" ?>

<sqlMap namespace="UserInfo" xmlns="http://ibatis.apache.org/mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >



  <alias>
    <!-- alias:取別名
                    assembly:表示類所在的文件
                    type:表示該類的完整的名稱
      -->
    <typeAlias alias="UserInfo" assembly="IBatisDemo.Model" type="IBatisDemo.Model.UserInfo" />
  </alias>



  <statements>

    <select id="select_UserInfoAll" resultMap="UserInfo-result">

      select Id,UserName,Age
      from UserInfo
    </select>
    <insert id="insert_UserInfoOne" parameterClass="UserInfo">
      INSERT INTO UserInfo(
      [UserName],[Age]
      )VALUES(
      #UserName#,#Age#
      )
      <selectKey  type="post" resultClass="int" property="Id">
        SELECT CAST(@@IDENTITY as int) as Id
      </selectKey>

    </insert>

    <delete id="del_UserInfoOne" parameterClass="UserInfo">
      <![CDATA[ 
        DELETE UserInfo
      ]]>
      <dynamic prepend="WHERE">
        Id = #Id#
      </dynamic>
    </delete>

    <select id="select_UserInfoOne" resultMap="UserInfo-result">
      select * from UserInfo
      <dynamic prepend="where">
        <isParameterPresent property="id" prepend="WHERE">
          [Id] = #Id#
        </isParameterPresent>
      </dynamic>
    </select>

    <update id="update_UserInfoOne" parameterClass="UserInfo">
      <![CDATA[ 
        UPDATE UserInfo
        SET
          UserName = #UserName#,
          Age = #Age#
      ]]>
      <dynamic prepend="WHERE">
        Id = #Id#
      </dynamic>
    </update>

  </statements>



  <resultMaps >

    <resultMap id="UserInfo-result" class="UserInfo">

      <result property="Id" column="Id" />

      <result property="UserName" column="UserName" />

      <result property="Age" column="Age" />

    </resultMap>

  </resultMaps>

</sqlMap>

  

說明:

statements 節點:

1

在這些容器標簽中有一些常用的屬性如下所示

1

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 

建立數據庫實體類:UserInfo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IBatisDemo.Model
{
    public class UserInfo
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public int Age { get; set; }
    }
}

  Mapper.cs 獲取Mapper的對象類:

using IBatisNet.Common.Utilities;
using IBatisNet.DataMapper;
using IBatisNet.DataMapper.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

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里面建立UserInfoService.cs 數據訪問

using IBatisDemo.Dao;
using IBatisDemo.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data.SqlClient;

namespace IBatisDemo.Service
{
    public class UserInfoService
    {
        public int UserInfoInsertOne(UserInfo userInfo)
        {
            Object obj = Mapper.GetMaper.Insert("UserInfo.insert_UserInfoOne", userInfo);
            return (int)obj;
        }

        public UserInfo GetUserInfo(int id)
        {
            return (UserInfo)Mapper.GetMaper.QueryForObject("UserInfo.select_UserInfoOne", id);
        }

        public IList<UserInfo> GetUserInfoList()
        {
            //xml里面配置的格式
            return Mapper.GetMaper.QueryForList<UserInfo>("UserInfo.select_UserInfoAll", null);
        }

        public int DelUserInfoOne(int id)
        {
            Object obj = Mapper.GetMaper.Delete("UserInfo.del_UserInfoOne", id);
            return (int)obj;
        }
        public int UpdateUserInfo(UserInfo userInfo)
        {
            Object obj = Mapper.GetMaper.Update("UserInfo.update_UserInfoOne", userInfo);
            return (int)obj;
        }
    }
}

  最后在web層 controller文件夾下建立 HomeController.cs   控制器

using IBatisDemo.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IBatisDemo.Model;

namespace IBatisDemo.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        UserInfoService service = new UserInfoService();
        #region 顯示員工
		 
	
        public ActionResult Index()
        {
            
            IList<UserInfo> userInfos = service.GetUserInfoList();
            ViewData["list"] = userInfos;
            return View();
        }

        #endregion

        #region 添加員工
        
        [HttpGet]
        public ActionResult UserInsert()
        {
            return View();
        }
        [HttpPost]
        public ActionResult UserInsert(UserInfo userInfo)
        {
            userInfo.UserName = Request["UserName"];
            userInfo.Age = int.Parse(Request["Age"]);
            if (service.UserInfoInsertOne(userInfo) > 0)
            {
                return Redirect("Index");
            }
            else
            {
                return Content("添加失敗");
            }


        }

        #endregion

        #region 刪除員工
        
        public ActionResult delUserInfo(int id)
        {
            id = int.Parse(Request["Id"]);
            if (service.DelUserInfoOne(id) > 0)
            {
                return Redirect("Index");

            }
            else
            {
                return Content("刪除失敗");
            }
        }
        #endregion

        #region 編輯員工資料
        [HttpGet]
        public ActionResult getUserInfo(int Id)
        {
            Id = int.Parse(Request["Id"]);
            UserInfo userInfos = service.GetUserInfo(Id);
            //ViewData["user"] = userInfos;
            return View(userInfos);
        }
        [HttpPost]
        public ActionResult getUserInfo(UserInfo userInfo)
        {
            userInfo.Id = int.Parse(Request["Id"]);
            userInfo.UserName = Request["UserName"];
            userInfo.Age = int.Parse(Request["Age"]);
            if (service.UpdateUserInfo(userInfo) > 0)
            {
                return Redirect("Index");
            }
            else
            {
                return Content("修改失敗");
            }
        }

        #endregion

    }
}

  View層  Index.cshtml

@{
    Layout = null;
}
@using IBatisDemo.Model
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        <h1>IBatis 學習Demo</h1>
        @if (ViewData["List"] != null)
        {
            <table style="width:100%;text-align:center;" id="tabs">
                <tr><th>編號</th><th>姓名</th><th>年齡</th><th>詳細</th><th>刪除</th><th>修改</th></tr>
                @foreach (var newInfo in (IList<UserInfo>)ViewData["List"])
                {
                    <tr>
                        <td>@newInfo.Id</td>
                        <td>@newInfo.UserName</td>
                        <td>@newInfo.Age</td>
                        <td><a href="javascript:void(0)" class="details" ids="@newInfo.Id">詳細</a></td>
                        <td><a href="/home/delUserInfo?Id=@newInfo.Id" class="deletes">刪除</a></td>
                        <td><a href="/home/getUserInfo?Id=@newInfo.Id" class="edits">修改</a></td>
                    </tr>
                }
            </table>
        }
        else
        {
            <span>暫無數據</span>
        }
        <a href="/home/UserInsert">添加</a>
    </div>
</body>
</html>

  編輯和添加的模板 直接在添加視圖的時候生成就可以了,源碼里面都有,這兒就不貼出來了

下面是運行效果:



 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM