zoukankan      html  css  js  c++  java
  • IBatis.net使用说明

      IBatis.net是移植于java版本,所以在.net平台上的操作和java平台上的操作基本没有什么太大的差别。严格来说,ibatis.net并不算的上是一种orm,因为它的sql语句均写到了配置文件中,没有自己专门的sql映射语句。但是相比Nhibernate来说,不仅简易,而且方便易学。学习成本还是很低的。

             回到正规话题上来,实例IBatis.net需要两个类库:IBatisNet.DataMapper.dll和IBatisNet.Common.dll,新建项目,我的项目结构如下:

     

    然后在使用ibatis.net框架的时候,需要配置三个config文件,第一个为database.config文件,里面则是配置数据库连接等信息的记录节点,如下图所示:

     

    第二个配置文件为providers.config,则记录了数据驱动的详细信息,可以通过在database.config中的provider节点来设置使用哪一个数据驱动。

    第三个配置文件为sqlmap.config,这个文件则是用来进行一些数据集方面的配置。

    需要注意的是,在项目中,所有的xml文件和.config文件,都需要设置为嵌入的资源才行。

    下面开始参看代码:

    首先是SQLHelper.cs的代码:

     

    View Code
    using IBatisNet.DataMapper;

    using System.Reflection;

    using System.IO;

    using IBatisNet.DataMapper.Configuration;

    using IBatisNet.DataMapper.Configuration.Statements;

    using IBatisNet.DataMapper.MappedStatements;

    using IBatisNet.DataMapper.Scope;

    using System.Data;

    using IBatisNet.Common;

    using System;



    namespace SQLMaps

    {

    publicclass SQLHelper

    {

    publicstatic ISqlMapper SqlMap;



    privatestaticreadonlyobject syncObj =newobject();



    ///<summary>

    /// ISqlMapper对象生成

    ///</summary>

    static SQLHelper()

    {

    if (SqlMap ==null)

    {

    lock (syncObj)

    {

    if (SqlMap ==null)

    {

    Assembly asembly
    = Assembly.Load("SQLMaps");

    Stream stream
    = asembly.GetManifestResourceStream("SQLMaps.sqlmap.config"); //得到xml数据流



    DomSqlMapBuilder builder
    =new DomSqlMapBuilder();

    SqlMap
    = builder.Configure(stream);

    }

    }

    }

    }



    ///<summary>

    /// 返回DataSet数据集

    ///</summary>

    publicstatic DataSet QueryForDataSet(string tag, object paramObject)

    {

    DataSet ds
    =new DataSet();

    IDbCommand command
    = GetDbCommand(tag,paramObject);

    SqlMap.LocalSession.CreateDataAdapter(command).Fill(ds);

    return ds;

    }



    ///<summary>

    /// 返回DataTable数据集

    ///</summary>

    publicstatic DataTable QueryForDataTable(string tag, object paramObject)

    {

    return QueryForDataSet(tag, paramObject).Tables[0];

    }



    ///<summary>

    /// 用于分页的DataTable数据集

    ///</summary>

    publicstatic DataTable QueryForDataTable(string tag, object paramObject, int PageSize, int curPage, outint recCount)

    {

    IDataReader dr
    =null;

    bool isSessionLocal =false;

    string sql = QueryForSql(tag,paramObject);

    string strCount ="select count(*) "+ sql.Substring(sql.ToLower().IndexOf("from"));



    IDalSession session
    = SqlMap.LocalSession;

    DataTable dt
    =new DataTable();

    if (session ==null)

    {

    session
    =new SqlMapSession(SqlMap);

    session.OpenConnection();

    isSessionLocal
    =true;

    }



    try

    {

    IDbCommand cmdCount
    = GetDbCommand(tag, paramObject);

    cmdCount.Connection
    = session.Connection;

    cmdCount.CommandText
    = strCount;

    object count = cmdCount.ExecuteScalar();

    recCount
    = Convert.ToInt32(count);



    IDbCommand cmd
    = GetDbCommand(tag, paramObject);

    cmd.Connection
    = session.Connection;

    dr
    = cmd.ExecuteReader();



    dt
    = QueryForPaging(dr, PageSize, curPage);

    }

    finally

    {

    if (isSessionLocal)

    {

    session.CloseConnection();

    }

    }

    return dt;

    }



    ///<summary>

    /// 获取数据

    ///</summary>

    protectedstatic DataTable QueryForPaging(IDataReader dataReader, int PageSize, int curPage)

    {

    DataTable dt
    =new DataTable();

    int colCount = dataReader.FieldCount;

    for (int i =0; i < colCount; i++)

    {

    dt.Columns.Add(
    new DataColumn(dataReader.GetName(i),dataReader.GetFieldType(i)));

    }



    //读取数据,将DataReader中的数据读取到DataTable中去

    object[] vald =newobject[colCount];

    int iCount =0; //临时记录变量

    while (dataReader.Read())

    {

    //当前记录在当前页记录范围内

    if (iCount >= PageSize * (curPage -1) && iCount < PageSize * curPage)

    {

    for (int i =0; i < colCount; i++)

    {

    vald[i]
    = dataReader.GetValue(i);

    }

    dt.Rows.Add(vald);

    }

    elseif (iCount > PageSize * curPage)

    {

    break;

    }

    iCount
    ++;

    }



    if (!dataReader.IsClosed)

    {

    dataReader.Close();

    dataReader.Dispose();

    }

    return dt;

    }

    }

    }

    具体的model类我就不说了,至于BLL类,则是根据配置文件来进行操作的,具体的如下:

     

    View Code
    public IList<Person> GetAllPerson()

    {

    return SqlMap.QueryForList<Person>("SelectAllPerson",null);

    }



    public DataTable GetAllPerson2()

    {

    int recCount =0;

    DataTable dt
    = SQLHelper.QueryForDataTable("SelectAllPerson2", new Person { FirstName ="kilo"},10,1,out recCount);

    return dt;

    }



    public DataTable GetAllPerson3()

    {

    return SQLHelper.QueryForDataTable("SelectAllPerson2", new Person { FirstName ="kilo"});

    }



    public Person GetPerson(int id)

    {

    return SqlMap.QueryForObject<Person>("",id);

    }



    publicint Create(Person person)

    {

    int Id = (int)SqlMap.Insert("InsertPerson",person);

    SqlMap.CommitTransaction();

    return Id;

    }



    publicvoid Update(Person person)

    {

    SqlMap.Update(
    "UpdatePerson",person);

    }



    publicvoid Delete(Person person)

    {

    SqlMap.Delete(
    "DeletePerson",person);

    }

    而这些操作是根据Person.xml的sql语句来的,具体内容如下:

     

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



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



    <alias>

    <typeAlias alias="Person" type="Model.Person,Model"/>

    </alias>



    <resultMaps>

    <resultMap id="SelectAllResult" class="Person">

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

    <result property="FirstName" column="PER_FIRST_NAME"/>

    <result property="LastName" column="PER_LAST_NAME"/>

    <result property="BirthDate" column="PER_BIRTH_DATE"/>

    <result property="WeightInKilograms" column="PER_WEIGHT_KG"/>

    <result property="HeightInMeters" column="PER_HEIGHT_M"/>

    </resultMap>

    </resultMaps>



    <statements>

    <select id="SelectAllPerson" resultMap="SelectAllResult">

    select

    PER_ID,

    PER_FIRST_NAME,

    PER_LAST_NAME,

    PER_BIRTH_DATE,

    PER_WEIGHT_KG,

    PER_HEIGHT_M

    from PERSON

    </select>



    <select id="SelectAllPerson2" resultMap="SelectAllResult">

    select

    PER_ID AS Id,

    PER_FIRST_NAME AS FirstName,

    PER_LAST_NAME AS LastName,

    PER_BIRTH_DATE AS BirthDate,

    PER_WEIGHT_KG AS WeightInKilograms,

    PER_HEIGHT_M AS HeightInMeters

    from PERSON

    <dynamic prepend="WHERE">

    <isParameterPresent>

    PER_FIRST_NAME LIKE #FirstName#+'%'

    </isParameterPresent>

    </dynamic>

    </select>



    <select id="SelectByPersonId" resultClass="Person" parameterClass="int">

    select

    PER_ID,

    PER_FIRST_NAME,

    PER_LAST_NAME,

    PER_BIRTH_DATE,

    PER_WEIGHT_KG,

    PER_HEIGHT_M

    from PERSON

    where PER_ID = #value#

    </select>



    <insert id="InsertPerson" parameterclass="Person">

    <selectKey property="Id" type="post" resultClass="int">

    ${selectKey}

    </selectKey>

    insert into Person

    ( PER_FIRST_NAME,

    PER_LAST_NAME,

    PER_BIRTH_DATE,

    PER_WEIGHT_KG,

    PER_HEIGHT_M)

    values

    (#FirstName#,#LastName#,#BirthDate#, #WeightInKilograms#, #HeightInMeters#)

    </insert>



    <update id="UpdatePerson"

    parameterclass
    ="Person">

    <![CDATA[ update Person set

    PER_FIRST_NAME =#FirstName#,

    PER_LAST_NAME =#LastName#,

    PER_BIRTH_DATE =#BirthDate#,

    PER_WEIGHT_KG=#WeightInKilograms#,

    PER_HEIGHT_M=#HeightInMeters#

    where

    PER_ID = #Id# 
    ]]>

    </update>



    <delete id="DeletePerson" parameterclass="Person">

    delete from Person

    where

    PER_ID = #Id#

    </delete>



    </statements>

    </sqlMap>

     

    下面的文章将会整合log4net开发,并且更加详细。谢谢

  • 相关阅读:
    【C++模版之旅】静态多态的讨论
    UBI(unsorted block image )块管理
    CSS多级数字序号的目录列表(类似3.3.1.这样的列表序号)
    MyBatis映射文件的resultMap如何做表关联
    爱上演讲的程序猿
    PHP中文汉字验证码
    设计模式之(二)Adapter模式
    sphinx全文检索之PHP使用教程
    [置顶] 【cocos2d-x入门实战】微信飞机大战之十三:游戏场景过渡
    计算机的族谱
  • 原文地址:https://www.cnblogs.com/scy251147/p/2084671.html
Copyright © 2011-2022 走看看