學習 ibatisnet + castle 筆記

1.  下載castle 和 ibatisnet 的 dll文件,

    注意:目前爲止,castle版本最高支持 ibatisnet 的 datamapper的版本是1.5,dataaccess 版本1.8
   
    所以需下載castle 1.0 和 ibatyisnet的 1.5 版本

2.  框架 模仿 npetshop2 的架構 並且稍做了簡化,去掉了其頁面採用castle控制的部分,具體框架如下:
   
    ATS.Domain  系統領域,所有數據庫實體的對象,數據載體,在其他各個層都要用到
    ATS.Persistence  持久層,持久化數據到數據庫,其中包括 interface(接口) 和 mapperDao(實現)
    ATS.Service  服務層,系統用到的所有業務方法,調用 ATS.Persistence層,其中包括 Implement(實現) 和 Interface(接口)
    ATS.Test  測試層 ,用 NUnit 測試
    ATS.Web   頁面層(最終與用戶交互)
    ATS.Common   系統公共層,公用方法和類

 

 

3.  首先需要配置 web.config 文件, 在<configuration>節點下新增 如下節點供castle使用

 


<?xml version="1.0"?>
<!--
    注意: 除了手動編輯此文件以外,您還可以使用
    Web 管理工具來配置應用程序的設置。可以使用 Visual Studio 中的
     “網站”->“Asp.Net 配置”選項。
    設置和註釋的完整列表在
    machine.config.comments 中,該文件通常位於
    WindowsMicrosoft.NetFrameworkv2.xConfig 中
-->
<configuration>
    <configSections>
        <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/>
    </configSections>

    <castle>
        <!--擴展castle 將 ibatisnet 當作插件和 castle 相結合-->
        <include uri="file://facilities.config"/>
        <!--此文件告訴castel 哪個接口 由 哪個類 實現-->
        <include uri="file://services.config"/>
    </castle>
   
    <appSettings/>
    <connectionStrings/>
    <system.web>
        <!--
            設置 compilation debug="true" 將調試符號插入
            已編譯的頁面中。但由於這會
            影響性能,因此只在開發過程中將此值
            設置爲 true。
        -->
        <compilation debug="true"/>
        <!--
            通過 <authentication> 節可以配置 ASP.NET 使用的
            安全身份驗證模式,
            以標識傳入的用戶。
        -->
        <authentication mode="Windows"/>
        <!--
            如果在執行請求的過程中出現未處理的錯誤,
            則通過 <customErrors> 節可以配置相應的處理步驟。具體說來,
            開發人員通過該節可以配置
            要顯示的 html 錯誤頁
            以代替錯誤堆棧跟蹤。

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
    </system.web>
</configuration>

使用以上配置時,需要將所有配置文件默認放在web應用程序的根目錄下,castle 會自動從 web.config中讀取

4.  配置 facilities.config 文件 (程序根目錄下)

 

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

        <facilities>
            <!--爲Castle 擴展 ibatisnet-->
            <facility id="ibatis" type="Castle.Facilities.IBatisNetIntegration.IBatisNetFacility, Castle.Facilities.IBatisNetIntegration" >
                <sqlMap id="sqlServerSqlMap" config="sqlMap.config" />
            </facility>
            <!--爲Castle 擴展 事務處理功能-->
            <facility id="transaction" type="Castle.Facilities.AutomaticTransactionManagement.TransactionFacility, Castle.Facilities.AutomaticTransactionManagement" />

        </facilities>
    </configuration>
這樣 castle 就可以自動將 ibatisnet 管理起來了,需要ibatisnet的時候會自動運行 ibatisnet

5.  配置 services.config 文件

 


<?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <components>
            <component
                      id="Employees"
                      service="ATS.Service.Interface.IEmployeesService, ATS.Service"
                      type="ATS.Service.Implement.EmployeesService, ATS.Service" />

        </components>
    </configuration>
可以發現: 服務(接口) IEmployeesService 由 EmployeesService 類實現 ,castle 會自動裝配,
    即在請求需要調用IEmployeesService 接口中的方法時,會自動實例化EmployeesService類,並調用其中相應的方法

6.  編寫ibatisnet 的配置文件 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="false"/>
        </settings>

        <!--database providers-->
        <providers resource="providers.config"/>

        <!-- Database connection information -->
        <database>
            <provider name="sqlServer2.0"/>
            <dataSource name="DocumentSystem" connectionString="server=.SQLExpress;database=Northwind;uid=sa;pwd="/>
        </database>

        <sqlMaps>
            <!--設置sqlmap,所有實體的數據庫操作-->
            <sqlMap resource="../ATS.Persistence/Maps/Employees.xml" />
        </sqlMaps>

    </sqlMapConfig>

以上設置 ibatisnet 對實體進行數據庫操作的 sqlmap.

7.  設置 dao.config 文件

 


<?xml version="1.0" encoding="utf-8"?>
    <daoConfig xmlns="http://ibatis.apache.org/dataAccess" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <!--Optional if resource-->

        <providers resource="providers.config"/>

        <context id="SqlMapDao" default="true">


            <!--==== Sql Server : SqlClient configuration =========-->


            <database>
                <provider name="sqlServer2.0"/>
                <dataSource name="Airfares" connectionString="server=.SQLExpress;database=Northwind;user id=sa;password=;"/>
            </database>

            <daoSessionHandler id="SqlMap">
                <property name="resource" value="sqlMap.config"/>
            </daoSessionHandler>

            <daoFactory>
                <dao interface="ATS.Persistence.Interface.IEmployeesDao, ATS.Persistence"
                    implementation="ATS.Persistence.MapperDao.EmployeesSqlMapDao, ATS.Persistence"/>
            </daoFactory>
        </context>

    </daoConfig>
主要是 <daoFactory> 節點, 設置 dao 運行時的接口對應的實現類,即:IEmployeesDao 由 EmployeesSqlMapDao實現


8. providers.config 可以從ibatisnet的幫助文檔裏找到,或去網站下載

    編寫 Employees.xml 文件 ,主要是編寫sql語句

 


<?xml version="1.0" encoding="UTF-8" ?>
    <sqlMap namespace="Employees" xmlns="http://ibatis.apache.org/mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <alias>
            <typeAlias alias="Employees" type="ATS.Domain.Employees, ATS.Domain" />
        </alias>
        <resultMaps>
            <resultMap id="SelectResult" class="Employees">
                <result property="EmployeeID" column="employeeid" />
                <result property="LastName" column="lastname" />
                <result property="FirstName" column="firstname" />
                <result property="Title" column="title" />
                <result property="TitleOfCourtesy" column="titleofcourtesy" />
                <result property="BirthDate" column="birthdate" />
                <result property="HireDate" column="hiredate" />
                <result property="Address" column="address" />
                <result property="City" column="city" />
                <result property="Region" column="region" />
                <result property="PostalCode" column="postalcode" />
                <result property="Country" column="country" />
                <result property="HomePhone" column="homephone" />
                <result property="Extension" column="extension" />
                <result property="Photo" column="photo" />
                <result property="Notes" column="notes" />
                <result property="ReportsTo" column="reportsto" />
                <result property="PhotoPath" column="photopath" />
            </resultMap>
        </resultMaps>
       
        <statements>
            <select id="SelectEmployees" parameterClass="int" resultMap="SelectResult">
                Select
                      employeeid,
                      lastname,
                      firstname,
                      title,
                      titleofcourtesy,
                      birthdate,
                      hiredate,
                      address,
                      city,
                      region,
                      postalcode,
                      country,
                      homephone,
                      extension,
                      photo,
                      notes,
                      reportsto,
                      photopath
                From Employees
                <dynamic prepend="WHERE">
                    <isParameterPresent>
                        employeeid=#EmployeeID#
                    </isParameterPresent>
                </dynamic>
            </select>
           
            <select id="BaseSelectEmployees" parameterClass="int" resultMap="SelectResult">
                Select
                      employeeid,
                      lastname,
                      firstname,
                      title,
                      titleofcourtesy,
                      birthdate,
                      hiredate,
                      address,
                      city,
                      region,
                      postalcode,
                      country,
                      homephone,
                      extension,
                      photo,
                      notes,
                      reportsto,
                      photopath
                From Employees
            </select>
           
            <select id="ChildSelectEmployees" parameterClass="int" resultMap="SelectResult" extends="BaseSelectEmployees">
               
            </select>
                   
            <insert id="InsertEmployees" parameterClass="Employees">
                Insert Into Employees (
                      employeeid,
                      lastname,
                      firstname,
                      title,
                      titleofcourtesy,
                      birthdate,
                      hiredate,
                      address,
                      city,
                      region,
                      postalcode,
                      country,
                      homephone,
                      extension,
                      photo,
                      notes,
                      reportsto,
                      photopath
                )Values(
                     #EmployeeID#,
                     #LastName#,
                     #FirstName#,
                     #Title#,
                     #TitleOfCourtesy#,
                     #BirthDate#,
                     #HireDate#,
                     #Address#,
                     #City#,
                     #Region#,
                     #PostalCode#,
                     #Country#,
                     #HomePhone#,
                     #Extension#,
                     #Photo#,
                     #Notes#,
                     #ReportsTo#,
                     #PhotoPath#
                )
            </insert>
           
            <update id="UpdateEmployees" parameterClass="Employees">
                Update Employees Set
                    employeeid=#EmployeeID#,
                    lastname=#LastName#,
                    firstname=#FirstName#,
                    title=#Title#,
                    titleofcourtesy=#TitleOfCourtesy#,
                    birthdate=#BirthDate#,
                    hiredate=#HireDate#,
                    address=#Address#,
                    city=#City#,
                    region=#Region#,
                    postalcode=#PostalCode#,
                    country=#Country#,
                    homephone=#HomePhone#,
                    extension=#Extension#,
                    photo=#Photo#,
                    notes=#Notes#,
                    reportsto=#ReportsTo#,
                    photopath=#PhotoPath#
                <dynamic prepend="WHERE">
                    <isParameterPresent>
                        employeeid=#EmployeeID#
                    </isParameterPresent>
                </dynamic>
            </update>
           
            <delete id="DeleteEmployees" parameterClass="int">
                Delete From Employees
                <dynamic prepend="WHERE">
                    <isParameterPresent>
                        employeeid=#EmployeeID#
                    </isParameterPresent>
                </dynamic>
            </delete>
           
        </statements>
    </sqlMap>
 

9.  接下來需要在 global中初始化 castle 容器:
    1. 定義自己的容器類,這樣可以在容器中初始化 ibatisnet的dao,即讀取dao.config文件,將接口和實現類保存起來,
       以後使用時直接取出即可,並在castle容器中加入DaoManager 對象實例 ,代碼如下:(此類放在ATS.Common 中)

 


        using System;
        using System.Configuration;
        using Castle.Windsor;
        using IBatisNet.DataAccess;
        using IBatisNet.DataAccess.Configuration;

        namespace ATS.Common
        ...{
            /**//// <summary>
            /// 自定義的容器類,初始化容器的時候,初始化dao,
            /// 定義好的持久層的接口和實現類加載
            /// </summary>
            public class ATSContainer : WindsorContainer
            ...{
                public ATSContainer(Castle.Windsor.Configuration.IConfigurationInterpreter inter) : base(inter)
                ...{
                    // Add DaoManager
                    DomDaoManagerBuilder builder = new DomDaoManagerBuilder();
                    builder.Configure(@"dao.config");

                    this.Kernel.AddComponentInstance("DaoManager", typeof(DaoManager), DaoManager.GetInstance("SqlMapDao"));
                }
            }
        }
 

2. global中初始化容器:

 


using System;
        using System.Data;
        using System.Configuration;
        using System.Collections;
        using System.Web;
        using System.Web.Security;
        using System.Web.SessionState;


        using Castle.Windsor;
        using Castle.Windsor.Configuration.Interpreters;
        using Castle.Core.Resource;
        using ATS.Common;

        namespace ATS.Web
        ...{
            public class Global : System.Web.HttpApplication, IContainerAccessor
            ...{

                private static WindsorContainer container;

                protected void Application_Start(object sender, EventArgs e)
                ...{
                    try
                    ...{
                        //初始化容器,採用從默認(從Web.config中讀取默認塊)文件中讀取
                        container = new ATSContainer(new XmlInterpreter(new ConfigResource()));
                    }
                    catch (ConfigurationException ex)
                    ...{
                        string msg = ex.Message;
                    }
                }

                protected void Application_End(object sender, EventArgs e)
                ...{
                    container.Dispose();
                }

                IContainerAccessor Members#region IContainerAccessor Members

                public IWindsorContainer Container
                ...{
                    get ...{ return container; }
                }

                #endregion
            }
        }
 

3. 在ATS.Common 中定義 ContainerAccessorUtil.cs類 ,此類主要用來獲取容器,
            在使用時可以從容器中取出接口:

           

 

//從容器中取出接口

IEmployeesService _IEmployeesService = (ContainerAccessorUtil.GetContainer())["Employees"] as IEmployeesService;
           
//並調用此接口的方法,系統會自動實例化實現IEmployeesService 的類,並調用其中的GetEmployeesList方法

IList<Employees> employees = _IEmployeesService.GetEmployeesList();


 

10. 定義實體類:(domain)

 

    namespace ATS.Domain
    ...{
        using System;
       
        /**//// <summary>
        /// Employees
        /// </summary>
        [Serializable]
        public class Employees
        ...{
            public Employees()
            ...{
               
            }
           
            private int _employeeid;
            private string _lastname;
            private string _firstname;
            private string _title;
            private string _titleofcourtesy;
            private DateTime _birthdate;
            private DateTime _hiredate;
            private string _address;
            private string _city;
            private string _region;
            private string _postalcode;
            private string _country;
            private string _homephone;
            private string _extension;
            private System.Byte[] _photo;
            private string _notes;
            private int _reportsto;
            private string _photopath;
           
            /**////<sumary>
            /// EmployeeID
            ///</sumary>
            public int EmployeeID
            ...{
                get...{return _employeeid;}
                set...{_employeeid = value;}
            }
            /**////<sumary>
            /// LastName
            ///</sumary>
            public string LastName
            ...{
                get...{return _lastname;}
                set...{_lastname = value;}
            }
            /**////<sumary>
            /// FirstName
            ///</sumary>
            public string FirstName
            ...{
                get...{return _firstname;}
                set...{_firstname = value;}
            }
            /**////<sumary>
            /// Title
            ///</sumary>
            public string Title
            ...{
                get...{return _title;}
                set...{_title = value;}
            }
            /**////<sumary>
            /// TitleOfCourtesy
            ///</sumary>
            public string TitleOfCourtesy
            ...{
                get...{return _titleofcourtesy;}
                set...{_titleofcourtesy = value;}
            }
            /**////<sumary>
            /// BirthDate
            ///</sumary>
            public DateTime BirthDate
            ...{
                get...{return _birthdate;}
                set...{_birthdate = value;}
            }
            /**////<sumary>
            /// HireDate
            ///</sumary>
            public DateTime HireDate
            ...{
                get...{return _hiredate;}
                set...{_hiredate = value;}
            }
            /**////<sumary>
            /// Address
            ///</sumary>
            public string Address
            ...{
                get...{return _address;}
                set...{_address = value;}
            }
            /**////<sumary>
            /// City
            ///</sumary>
            public string City
            ...{
                get...{return _city;}
                set...{_city = value;}
            }
            /**////<sumary>
            /// Region
            ///</sumary>
            public string Region
            ...{
                get...{return _region;}
                set...{_region = value;}
            }
            /**////<sumary>
            /// PostalCode
            ///</sumary>
            public string PostalCode
            ...{
                get...{return _postalcode;}
                set...{_postalcode = value;}
            }
            /**////<sumary>
            /// Country
            ///</sumary>
            public string Country
            ...{
                get...{return _country;}
                set...{_country = value;}
            }
            /**////<sumary>
            /// HomePhone
            ///</sumary>
            public string HomePhone
            ...{
                get...{return _homephone;}
                set...{_homephone = value;}
            }
            /**////<sumary>
            /// Extension
            ///</sumary>
            public string Extension
            ...{
                get...{return _extension;}
                set...{_extension = value;}
            }
            /**////<sumary>
            /// Photo
            ///</sumary>
            public System.Byte[] Photo
            ...{
                get...{return _photo;}
                set...{_photo = value;}
            }
            /**////<sumary>
            /// Notes
            ///</sumary>
            public string Notes
            ...{
                get...{return _notes;}
                set...{_notes = value;}
            }
            /**////<sumary>
            /// ReportsTo
            ///</sumary>
            public int ReportsTo
            ...{
                get...{return _reportsto;}
                set...{_reportsto = value;}
            }
            /**////<sumary>
            /// PhotoPath
            ///</sumary>
            public string PhotoPath
            ...{
                get...{return _photopath;}
                set...{_photopath = value;}
            }
        }
    }
 

11.  定義ATS.Persistence.Interface.IEmployeesDao.cs 類

 


    namespace ATS.Persistence.MapperDao
    ...{
        using System;
        using System.Collections;
        using System.Collections.Generic;
        using IBatisNet.Common;
        using IBatisNet.DataMapper;
        using IBatisNet.Common.Exceptions;

        using ATS.Domain;
        using ATS.Persistence.Interface;

        /**//// <summary>
        /// EmployeesSqlMapDao
        /// </summary>
        public class EmployeesSqlMapDao : BaseSqlMapDao, IEmployeesDao
        ...{
            public EmployeesSqlMapDao ()
            ...{
                //
                // TODO: 此處添加EmployeesSqlMapDao的構造函數
                //
            }

            /**//// <summary>
            /// 得到列表
            /// </summary>
            public IList<Employees> GetEmployeesList()
            ...{
                return ExecuteQueryForList<Employees>("SelectEmployees",null);
            }

            /**//// <summary>
            /// 新建
            /// </summary>
            public void AddEmployees(Employees employees)
            ...{
                ExecuteInsert("InsertEmployees",employees);
            }
            /**//// <summary>
            /// 修改
            /// </summary>
            public void UpdateEmployees(Employees employees)
            ...{
                ExecuteUpdate("UpdateEmployees",employees);
            }
           
            /**//// <summary>
            /// 得到明細
            /// </summary>
            /// <param name="id"></param>
            /// <returns></returns>
            public Employees GetEmployeesDetail(System.Int32 EmployeeID)
            ...{
                return ExecuteQueryForObject<Employees>("SelectEmployees",EmployeeID);
            }

            /**//// <summary>
            /// 刪除
            /// </summary>
            /// <param name="id"></param>
            public void DeleteEmployees(System.Int32 EmployeeID)
            ...{
                ExecuteDelete("DeleteEmployees",EmployeeID);
            }
           

        }
    }
BaseSqlMapDao.cs 文件

 

 

using System;
using System.Collections;
using System.Collections.Generic;
using IBatisNet.Common.Pagination;
using IBatisNet.DataMapper;
using IBatisNet.DataMapper.Exceptions;
using IBatisNet.DataMapper.Configuration;
using IBatisNet.DataAccess;
using IBatisNet.DataAccess.DaoSessionHandlers;
using IBatisNet.DataAccess.Exceptions;
using IBatisNet.DataAccess.Interfaces;
using IBatisNet.Common.Utilities;
using ATS.Common;

namespace ATS.Persistence.MapperDao
...{
    /**//// <summary>
    /// Summary description for BaseSqlMapDao.
    /// </summary>
    public class BaseSqlMapDao : IDao
    ...{
        protected const int PAGE_SIZE = 4;

        /**//// <summary>
        /// 創建並返回一個sqlmap對象
        /// (下面對持久層的操作,都需要用到)
        /// Looks up the parent DaoManager, gets the local transaction
        /// (which should be a SqlMapDaoTransaction) and returns the
        /// SqlMap associated with this DAO.
        /// </summary>
        /// <returns>The SqlMap instance for this DAO.</returns>
        protected SqlMapper GetLocalSqlMap()
        ...{
            //通過DaoManager獲取本地的SqlMapper對象
            DaoManager daoManager = DaoManager.GetInstance(this) as DaoManager;
            SqlMapDaoSession sqlMapDaoSession = (SqlMapDaoSession)daoManager.LocalDaoSession;

            return sqlMapDaoSession.SqlMap as SqlMapper;
        }

        非泛型方法#region 非泛型方法
        /**//// <summary>
        /// Simple convenience method to wrap the SqlMap method of the same name.
        /// Wraps the exception with a DataAccessException to isolate the SqlMap framework.
        /// </summary>
        /// <param name="statementName"></param>
        /// <param name="parameterObject"></param>
        /// <returns></returns>
        protected IList ExecuteQueryForList(string statementName, object parameterObject)
        ...{
            SqlMapper sqlMap = GetLocalSqlMap();
            try
            ...{
                return sqlMap.QueryForList(statementName, parameterObject);
            }
            catch (Exception e)
            ...{
                throw new DataMapperException("Error executing query ''" + statementName + "'' for list.  Cause: " + e.Message, e);
            }
        }

        /**//// <summary>
        /// Simple convenience method to wrap the SqlMap method of the same name.
        /// Wraps the exception with a DataAccessException to isolate the SqlMap framework.
        /// </summary>
        /// <param name="statementName"></param>
        /// <param name="parameterObject"></param>
        /// <param name="skipResults"></param>
        /// <param name="maxResults"></param>
        /// <returns></returns>
        protected IList ExecuteQueryForList(string statementName, object parameterObject, int skipResults, int maxResults)
        ...{
            SqlMapper sqlMap = GetLocalSqlMap();
            try
            ...{
                return sqlMap.QueryForList(statementName, parameterObject, skipResults, maxResults);
            }
            catch (Exception e)
            ...{
                throw new DataMapperException("Error executing query ''" + statementName + "'' for list.  Cause: " + e.Message, e);
            }
        }

        /**//// <summary>
        /// Simple convenience method to wrap the SqlMap method of the same name.
        /// Wraps the exception with a DataAccessException to isolate the SqlMap framework.
        /// </summary>
        /// <param name="statementName"></param>
        /// <param name="parameterObject"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        protected IPaginatedList ExecuteQueryForPaginatedList(string statementName, object parameterObject, int pageSize)
        ...{
            SqlMapper sqlMap = GetLocalSqlMap();
            try
            ...{
                return sqlMap.QueryForPaginatedList(statementName, parameterObject, pageSize);
            }
            catch (Exception e)
            ...{
                throw new DataMapperException("Error executing query ''" + statementName + "'' for paginated list.  Cause: " + e.Message, e);
            }
        }

        /**//// <summary>
        /// Simple convenience method to wrap the SqlMap method of the same name.
        /// Wraps the exception with a DataAccessException to isolate the SqlMap framework.
        /// </summary>
        /// <param name="statementName"></param>
        /// <param name="parameterObject"></param>
        /// <returns></returns>
        protected object ExecuteQueryForObject(string statementName, object parameterObject)
        ...{
            SqlMapper sqlMap = GetLocalSqlMap();

            try
            ...{
                return sqlMap.QueryForObject(statementName, parameterObject);
            }
            catch (Exception e)
            ...{
                throw new DataMapperException("Error executing query ''" + statementName + "'' for object.  Cause: " + e.Message, e);
            }
        }

        /**//// <summary>
        /// Simple convenience method to wrap the SqlMap method of the same name.
        /// Wraps the exception with a DataAccessException to isolate the SqlMap framework.
        /// </summary>
        /// <param name="statementName"></param>
        /// <param name="parameterObject"></param>
        /// <returns></returns>
        protected int ExecuteUpdate(string statementName, object parameterObject)
        ...{
            SqlMapper sqlMap = GetLocalSqlMap();

            try
            ...{
                return sqlMap.Update(statementName, parameterObject);
            }
            catch (Exception e)
            ...{
                throw new DataMapperException("Error executing query ''" + statementName + "'' for update.  Cause: " + e.Message, e);
            }
        }

        /**//// <summary>
        /// Simple convenience method to wrap the SqlMap method of the same name.
        /// Wraps the exception with a DataAccessException to isolate the SqlMap framework.
        /// </summary>
        /// <param name="statementName"></param>
        /// <param name="parameterObject"></param>
        /// <returns></returns>
        protected object ExecuteInsert(string statementName, object parameterObject)
        ...{
            SqlMapper sqlMap = GetLocalSqlMap();

            try
            ...{
                return sqlMap.Insert(statementName, parameterObject);
            }
            catch (Exception e)
            ...{
                throw new DataMapperException("Error executing query ''" + statementName + "'' for insert.  Cause: " + e.Message, e);
            }
        }
        #endregion

        泛型方法#region 泛型方法

        /**//// <summary>
        /// 得到列表
        /// </summary>
        /// <typeparam name="T">實體類型</typeparam>
        /// <param name="statementName">操作名稱,對應xml中的Statement的id</param>
        /// <param name="parameterObject">參數</param>
        /// <returns></returns>
        protected IList<T> ExecuteQueryForList<T>(string statementName, object parameterObject)
        ...{
            SqlMapper sqlMap = GetLocalSqlMap();

            try
            ...{
                return sqlMap.QueryForList<T>(statementName, parameterObject);
            }
            catch (Exception e)
            ...{
                throw new DataMapperException("Error executing query ''" + statementName + "'' for list.  Cause: " + e.Message, e);
            }
        }

        /**//// <summary>
        /// 得到指定數量的記錄數
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="statementName"></param>
        /// <param name="parameterObject">參數</param>
        /// <param name="skipResults">跳過的記錄數</param>
        /// <param name="maxResults">最大返回的記錄數</param>
        /// <returns></returns>
        protected IList<T> ExecuteQueryForList<T>(string statementName, object parameterObject, int skipResults, int maxResults)
        ...{
            SqlMapper sqlMap = GetLocalSqlMap();

            try
            ...{
                return sqlMap.QueryForList<T>(statementName, parameterObject, skipResults, maxResults);
            }
            catch (Exception e)
            ...{
                throw new DataMapperException("Error executing query ''" + statementName + "'' for list.  Cause: " + e.Message, e);
            }
        }

        /**//// <summary>
        /// 查詢得到對象的一個實例
        /// </summary>
        /// <typeparam name="T">對象type</typeparam>
        /// <param name="statementName">操作名</param>
        /// <param name="parameterObject">參數</param>
        /// <returns></returns>
        protected T ExecuteQueryForObject<T>(string statementName, object parameterObject)
        ...{
            SqlMapper sqlMap = GetLocalSqlMap();

            try
            ...{
                return sqlMap.QueryForObject<T>(statementName, parameterObject);
            }
            catch (Exception e)
            ...{
                throw new DataMapperException("Error executing query ''" + statementName + "'' for object.  Cause: " + e.Message, e);
            }
        }

        /**//// <summary>
        /// 執行刪除
        /// </summary>
        /// <param name="statementName">操作名</param>
        /// <param name="parameterObject">參數</param>
        protected void ExecuteDelete(string statementName, object parameterObject)
        ...{
            SqlMapper sqlMap = GetLocalSqlMap();

            try
            ...{
                sqlMap.Delete(statementName, parameterObject);
            }
            catch (Exception e)
            ...{
                throw new DataMapperException("Error executing query ''" + statementName + "'' for delete.  Cause: " + e.Message, e);
            }
        }

        #endregion
    }
}
13. 定義 ATS.Service.Interface.IEmployeesService.cs 類

 

 

    using System;
    using System.Collections.Generic;
    using System.Text;

    using ATS.Domain;

    namespace ATS.Service.Interface
    ...{
        public interface IEmployeesService
        ...{
            /**//// <summary>
            /// 得到列表
            /// </summary>
            IList<Employees> GetEmployeesList();

        }
    }
14. 定義 ATS.Service.Implement.EmployeesService.cs 類

 

 

    using System;
    using System.Collections.Generic;
    using System.Text;

    using ATS.Persistence.Interface;
    using ATS.Persistence.MapperDao;
    using ATS.Service.Interface;
    using ATS.Domain;
    using IBatisNet.DataAccess;

    namespace ATS.Service.Implement
    ...{
        public class EmployeesService : IEmployeesService
        ...{
            Private Fields#region Private Fields
            private IEmployeesDao _employeesDao = null;
            private DaoManager _daoManager = null;
            #endregion

            Constructor#region Constructor
            public EmployeesService(DaoManager daoManager)
            ...{
                _daoManager = daoManager;
                _employeesDao = _daoManager.GetDao( typeof(IEmployeesDao) ) as IEmployeesDao;
            }
            #endregion

            /**//// <summary>
            /// 得到列表
            /// </summary>
            public IList<Employees> GetEmployeesList()
            ...{
                return _employeesDao.GetEmployeesList();
            }

        }
    }
最後 在頁面的aspx.cs文件中調用了, 將數據顯示在 gridview 中;
以下是調用代碼

 

 

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using ATS.Domain;
using ATS.Service.Implement;
using ATS.Service.Interface;
using ATS.Common;
using System.Collections.Generic;

using ATS.Common;

namespace ATS.Web
...{
    public partial class TestForm : System.Web.UI.Page
    ...{
        IEmployeesService _IEmployeesService = null;

        protected void Page_Load(object sender, EventArgs e)
        ...{
            //從容器中取出接口(從services.config中的ID獲取)
            _IEmployeesService = (ContainerAccessorUtil.GetContainer())["Employees"] as IEmployeesService;
           
            if (!IsPostBack)
            ...{
                BindData();
            }
        }

        public void BindData()
        ...{
            //使用接口的方法,容器會自動查找並調用實現類中的方法
            IList<Employees> employees = _IEmployeesService.GetEmployeesList();

            dgData.DataSource = employees;
            dgData.DataBind();
        }
    }

   
}

發佈了2 篇原創文章 · 獲贊 0 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章