天天看点

iBatis for net 框架使用

简介:ibatis 一词来源于“internet”和“abatis”的组合,是一个由Clinton Begin在2001年发起的开放源代码项目,到后面发展的版本叫MyBatis但都是指的同一个东西。最初侧重于密码软件的开发,现在是一个基于Java的持久层框架,渐渐的也把这种模式转移到了net。相对NHibernate等“一站式”ORM解决方案而言,ibatis 是一种“半自动化”的ORM实现。

下载地址:http://code.google.com/p/mybatisnet/downloads/list?can=3 

本文开发Demo环境:IBatis.DataMapper.1.6.2.bin + MsSql 2005 + Vs 2010

使用步骤:

在使用之前,为大家推荐一款代码生成器,也是我专为此框架写的一款代码生成器,生成iBatis的Map配置文件,这样一来,用户不用开任何关于框架的说明文档,即可使用此框架。代码生成器(CodeHelper)下载地址与说明:

http://www.cnblogs.com/stone_w/archive/2011/09/26/2192010.html

第一步:创建数据库与新建网站项目。

创建数据库与表的T-sql:

/*

* iBatisDemo Sql

* Stone (QQ:1370569)

* Date:2011.09.26

*/

create database OrmDB

go

use OrmDB

create table People

(

id int primary key identity,

[name] varchar(250),

age int

)

打开vs开发工具,新建网站项目。

第二步:为网站添加iBatis框架支持。

为网站添加引用或者直接把下载的iBatis框架中的IBatisNet.Common.dll和IBatisNet.DataMapper.dll复制到Bin目录下。

第三步:添加iBatis配置文件。

iBatis的配置文件只用三种,也必须要有这三种:

1.providers.config[文件名不能修改]此文件为数据库开发商提供的驱动配置集合,是固定不变的,无需修改与配置,复制文件到网站的根目录,代码如下:

iBatis for net 框架使用
iBatis for net 框架使用
providers.config

<?xml version="1.0" encoding="utf-8"?>
<providers
xmlns="http://ibatis.apache.org/providers"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<clear/>
<provider
name="sqlServer1.0"
          description="Microsoft SQL Server, provider V1.0.3300.0 in framework .NET V1.0"
          enabled="false"
          assemblyName="System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" connectionClass="System.Data.SqlClient.SqlConnection"
          commandClass="System.Data.SqlClient.SqlCommand"
          parameterClass="System.Data.SqlClient.SqlParameter"
          parameterDbTypeClass="System.Data.SqlDbType"
          parameterDbTypeProperty="SqlDbType"
          dataAdapterClass="System.Data.SqlClient.SqlDataAdapter"
          commandBuilderClass="System.Data.SqlClient.SqlCommandBuilder"
          usePositionalParameters="false"
          useParameterPrefixInSql="true"
          useParameterPrefixInParameter="true"
          parameterPrefix="@"
          allowMARS="false"
/>
<provider
name="sqlServer1.1"
          description="Microsoft SQL Server, provider V1.0.5000.0 in framework .NET V1.1"
          enabled="false"
          assemblyName="System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
          connectionClass="System.Data.SqlClient.SqlConnection"
          commandClass="System.Data.SqlClient.SqlCommand"
          parameterClass="System.Data.SqlClient.SqlParameter"
          parameterDbTypeClass="System.Data.SqlDbType"
          parameterDbTypeProperty="SqlDbType"
          dataAdapterClass="System.Data.SqlClient.SqlDataAdapter"
          commandBuilderClass="System.Data.SqlClient.SqlCommandBuilder"
          usePositionalParameters="false"
          useParameterPrefixInSql="true"
          useParameterPrefixInParameter="true"
          parameterPrefix="@"
          allowMARS="false"
/>
<provider
name="sqlServer2.0"
        enabled="true"
        description="Microsoft SQL Server, provider V2.0.0.0 in framework .NET V2.0"
        assemblyName="System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
        connectionClass="System.Data.SqlClient.SqlConnection"
        commandClass="System.Data.SqlClient.SqlCommand"
        parameterClass="System.Data.SqlClient.SqlParameter"
        parameterDbTypeClass="System.Data.SqlDbType"
        parameterDbTypeProperty="SqlDbType"
        dataAdapterClass="System.Data.SqlClient.SqlDataAdapter"
        commandBuilderClass=" System.Data.SqlClient.SqlCommandBuilder"
        usePositionalParameters = "false"
        useParameterPrefixInSql = "true"
        useParameterPrefixInParameter = "true"
        parameterPrefix="@"
        allowMARS="false"
/>
<provider
name="sqlServer2005"
       enabled="false"
       description="Microsoft SQL Server, provider V2.0.0.0 in framework .NET V2.0"
       assemblyName="System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
       connectionClass="System.Data.SqlClient.SqlConnection"
       commandClass="System.Data.SqlClient.SqlCommand"
       parameterClass="System.Data.SqlClient.SqlParameter"
       parameterDbTypeClass="System.Data.SqlDbType"
       parameterDbTypeProperty="SqlDbType"
       dataAdapterClass="System.Data.SqlClient.SqlDataAdapter"
       commandBuilderClass=" System.Data.SqlClient.SqlCommandBuilder"
       usePositionalParameters = "false"
       useParameterPrefixInSql = "true"
       useParameterPrefixInParameter = "true"
       parameterPrefix="@"
       allowMARS="true"
/>
<provider name="OleDb1.1"
        description="OleDb, provider V1.0.5000.0 in framework .NET V1.1"
        enabled="false"
        assemblyName="System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
        connectionClass="System.Data.OleDb.OleDbConnection"
        commandClass="System.Data.OleDb.OleDbCommand"
        parameterClass="System.Data.OleDb.OleDbParameter"
        parameterDbTypeClass="System.Data.OleDb.OleDbType"
        parameterDbTypeProperty="OleDbType"
        dataAdapterClass="System.Data.OleDb.OleDbDataAdapter"
        commandBuilderClass="System.Data.OleDb.OleDbCommandBuilder"
        usePositionalParameters="true"
        useParameterPrefixInSql="false"
        useParameterPrefixInParameter="false"
        parameterPrefix=""
        allowMARS="false"
/>
<provider name="OleDb2.0"
      description="OleDb, provider V2.0.0.0 in framework .NET V2"
      enabled="false"
      assemblyName="System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
      connectionClass="System.Data.OleDb.OleDbConnection"
      commandClass="System.Data.OleDb.OleDbCommand"
      parameterClass="System.Data.OleDb.OleDbParameter"
      parameterDbTypeClass="System.Data.OleDb.OleDbType"
      parameterDbTypeProperty="OleDbType"
      dataAdapterClass="System.Data.OleDb.OleDbDataAdapter"
      commandBuilderClass="System.Data.OleDb.OleDbCommandBuilder"
      usePositionalParameters="true"
      useParameterPrefixInSql="false"
      useParameterPrefixInParameter="false"
      parameterPrefix=""
      allowMARS="false"
/>
<provider
name="Odbc1.1"
      description="Odbc, provider V1.0.5000.0 in framework .NET V1.1"
      enabled="false"
      assemblyName="System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
      connectionClass="System.Data.Odbc.OdbcConnection"
      commandClass="System.Data.Odbc.OdbcCommand"
      parameterClass="System.Data.Odbc.OdbcParameter"
      parameterDbTypeClass="System.Data.Odbc.OdbcType"
      parameterDbTypeProperty="OdbcType"
      dataAdapterClass="System.Data.Odbc.OdbcDataAdapter"
      commandBuilderClass="System.Data.Odbc.OdbcCommandBuilder"
      usePositionalParameters="true"
      useParameterPrefixInSql="false"
      useParameterPrefixInParameter="false"
      parameterPrefix="@"
      allowMARS="false"
/>
<provider
name="Odbc2.0"
      description="Odbc, provider V2.0.0.0 in framework .NET V2"
      enabled="false"
      assemblyName="System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
      connectionClass="System.Data.Odbc.OdbcConnection"
      commandClass="System.Data.Odbc.OdbcCommand"
      parameterClass="System.Data.Odbc.OdbcParameter"
      parameterDbTypeClass="System.Data.Odbc.OdbcType"
      parameterDbTypeProperty="OdbcType"
      dataAdapterClass="System.Data.Odbc.OdbcDataAdapter"
      commandBuilderClass="System.Data.Odbc.OdbcCommandBuilder"
      usePositionalParameters="true"
      useParameterPrefixInSql="false"
      useParameterPrefixInParameter="false"
      parameterPrefix="@"
      allowMARS="false"
/>
<provider
name="oracle9.2"
      description="Oracle, Oracle provider V9.2.0.401"
      enabled="false"
      assemblyName="Oracle.DataAccess, Version=9.2.0.401, Culture=neutral, PublicKeyToken=89b483f429c47342" connectionClass="Oracle.DataAccess.Client.OracleConnection"
      commandClass="Oracle.DataAccess.Client.OracleCommand"
      parameterClass="Oracle.DataAccess.Client.OracleParameter"
      parameterDbTypeClass="Oracle.DataAccess.Client.OracleDbType"
      parameterDbTypeProperty="OracleDbType"
      dataAdapterClass="Oracle.DataAccess.Client.OracleDataAdapter"
      commandBuilderClass="Oracle.DataAccess.Client.OracleCommandBuilder"
      usePositionalParameters="false"
      useParameterPrefixInSql="true"
      useParameterPrefixInParameter="false"
      parameterPrefix=":"
      useDeriveParameters="false"
      allowMARS="false"
/>
<provider
name="oracle10.1"
      description="Oracle, oracle provider V10.1.0.301"
      enabled="false"
      assemblyName="Oracle.DataAccess, Version=10.1.0.301, Culture=neutral, PublicKeyToken=89b483f429c47342" connectionClass="Oracle.DataAccess.Client.OracleConnection"
      commandClass="Oracle.DataAccess.Client.OracleCommand"
      parameterClass="Oracle.DataAccess.Client.OracleParameter"
      parameterDbTypeClass="Oracle.DataAccess.Client.OracleDbType"
      parameterDbTypeProperty="OracleDbType"
      dataAdapterClass="Oracle.DataAccess.Client.OracleDataAdapter"
      commandBuilderClass="Oracle.DataAccess.Client.OracleCommandBuilder"
      usePositionalParameters="true"
      useParameterPrefixInSql="true"
      useParameterPrefixInParameter="true"
      parameterPrefix=":"
      useDeriveParameters="false"
      allowMARS="false"
/>
<provider
name="oracleClient1.0"
      description="Oracle, Microsoft provider V1.0.5000.0"
      enabled="false"
      assemblyName="System.Data.OracleClient, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" connectionClass="System.Data.OracleClient.OracleConnection"
      commandClass="System.Data.OracleClient.OracleCommand"
      parameterClass="System.Data.OracleClient.OracleParameter"
      parameterDbTypeClass="System.Data.OracleClient.OracleType"
      parameterDbTypeProperty="OracleType"
      dataAdapterClass="System.Data.OracleClient.OracleDataAdapter"
      commandBuilderClass="System.Data.OracleClient.OracleCommandBuilder"
      usePositionalParameters="false"
      useParameterPrefixInSql="true"
      useParameterPrefixInParameter="false"
      parameterPrefix=":"
      allowMARS="false"
/>
<provider
name="ByteFx"
      description="MySQL, ByteFx provider V0.7.6.15073"
      enabled="false"
      assemblyName="ByteFX.MySqlClient, Version=0.7.6.15073, Culture=neutral, PublicKeyToken=f2fef6fed1732fc1" connectionClass="ByteFX.Data.MySqlClient.MySqlConnection"
      commandClass="ByteFX.Data.MySqlClient.MySqlCommand"
      parameterClass="ByteFX.Data.MySqlClient.MySqlParameter"
      parameterDbTypeClass="ByteFX.Data.MySqlClient.MySqlDbType"
      parameterDbTypeProperty="MySqlDbType"
      dataAdapterClass="ByteFX.Data.MySqlClient.MySqlDataAdapter"
      commandBuilderClass="ByteFX.Data.MySqlClient.MySqlCommandBuilder"
      usePositionalParameters="false"
      useParameterPrefixInSql="true"
      useParameterPrefixInParameter="true"
      parameterPrefix="@"
      allowMARS="false"
/>
<provider
name="MySql"
      description="MySQL, MySQL provider 1.0.7.30072"
      enabled="false"
      assemblyName="MySql.Data, Version=1.0.7.30072, Culture=neutral, PublicKeyToken=c5687fc88969c44d" connectionClass="MySql.Data.MySqlClient.MySqlConnection"
      commandClass="MySql.Data.MySqlClient.MySqlCommand"
      parameterClass="MySql.Data.MySqlClient.MySqlParameter"
      parameterDbTypeClass="MySql.Data.MySqlClient.MySqlDbType"
      parameterDbTypeProperty="MySqlDbType"
      dataAdapterClass="MySql.Data.MySqlClient.MySqlDataAdapter"
      commandBuilderClass="MySql.Data.MySqlClient.MySqlCommandBuilder"
      usePositionalParameters="false"
      useParameterPrefixInSql="true"
      useParameterPrefixInParameter="true"
      parameterPrefix="?"
      allowMARS="false"
/>
<provider name="SQLite3 Finisar"
      description="SQLite, SQLite.NET provider V0.21.1869.3794"
      enabled="false"
      assemblyName="SQLite.NET, Version=0.21.1869.3794, Culture=neutral, PublicKeyToken=c273bd375e695f9c"
      connectionClass="Finisar.SQLite.SQLiteConnection"
      commandClass="Finisar.SQLite.SQLiteCommand"
      parameterClass="Finisar.SQLite.SQLiteParameter"
      parameterDbTypeClass="System.Data.DbType, System.Data"
      parameterDbTypeProperty="DbType"
      dataAdapterClass="Finisar.SQLite.SQLiteDataAdapter"
      commandBuilderClass="Finisar.SQLite.SQLiteCommandBuilder"
      usePositionalParameters="false"
      useParameterPrefixInSql="true"
      useParameterPrefixInParameter="true"
      parameterPrefix="@"
      setDbParameterPrecision="false"
      setDbParameterScale="false"
      allowMARS="false"
/>
<provider name="SQLite3"
      description="SQLite, SQLite.NET provider V1.0.43.0"
      enabled="false"
      assemblyName="System.Data.SQLite, Version=1.0.43.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139"
      connectionClass="System.Data.SQLite.SQLiteConnection"
      commandClass="System.Data.SQLite.SQLiteCommand"
      parameterClass="System.Data.SQLite.SQLiteParameter"
      parameterDbTypeClass="System.Data.SQLite.SQLiteType"
      parameterDbTypeProperty="DbType"
      dataAdapterClass="System.Data.SQLite.SQLiteDataAdapter"
      commandBuilderClass="System.Data.SQLite.SQLiteCommandBuilder"
      usePositionalParameters="false"
      useParameterPrefixInSql="true"
      useParameterPrefixInParameter="true"
      parameterPrefix="@"
      setDbParameterPrecision="false"
      setDbParameterScale="false"
      allowMARS="false"
/>
<provider
name="Firebird1.7"
      description="Firebird, Firebird SQL .NET provider V1.7.0.33200"
      enabled="false"
      assemblyName="FirebirdSql.Data.Firebird, Version=1.7.0.33200, Culture=neutral, PublicKeyToken=fa843d180294369d" connectionClass="FirebirdSql.Data.Firebird.FbConnection"
      commandClass="FirebirdSql.Data.Firebird.FbCommand"
      parameterClass="FirebirdSql.Data.Firebird.FbParameter"
      parameterDbTypeClass="FirebirdSql.Data.Firebird.FbDbType"
      parameterDbTypeProperty="FbDbType"
      dataAdapterClass="FirebirdSql.Data.Firebird.FbDataAdapter"
      commandBuilderClass="FirebirdSql.Data.Firebird.FbCommandBuilder"
      usePositionalParameters="false"
      useParameterPrefixInSql="true"
      useParameterPrefixInParameter="true"
      parameterPrefix="@"
      allowMARS="false"
/>
<provider
name="PostgreSql0.99.1.0"
      description="PostgreSql, Npgsql provider V0.99.1.0"
      enabled="false"
      assemblyName="Npgsql, Version=0.99.1.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7"
      connectionClass="Npgsql.NpgsqlConnection"
      commandClass="Npgsql.NpgsqlCommand"
      parameterClass="Npgsql.NpgsqlParameter"
      parameterDbTypeClass="NpgsqlTypes.NpgsqlDbType"
      parameterDbTypeProperty="NpgsqlDbType"
      dataAdapterClass="Npgsql.NpgsqlDataAdapter"
      commandBuilderClass="Npgsql.NpgsqlCommandBuilder"
      usePositionalParameters="false"
      useParameterPrefixInSql="true"
      useParameterPrefixInParameter="true"
      parameterPrefix=":"
      allowMARS="true"
/>
<provider
name="iDb2.10"
      description="IBM DB2 Provider, V 10.0"
      enabled="false"
      assemblyName="IBM.Data.DB2.iSeries, Version=10.0.0.0,Culture=neutral, PublicKeyToken=9cdb2ebfb1f93a26, Custom=null" connectionClass="IBM.Data.DB2.iSeries.iDB2Connection"
      commandClass="IBM.Data.DB2.iSeries.iDB2Command"
      parameterClass="IBM.Data.DB2.iSeries.iDB2Parameter"
      parameterDbTypeClass="IBM.Data.DB2.iSeries.iDB2DbType"
      parameterDbTypeProperty="iDB2DbType"
      dataAdapterClass="IBM.Data.DB2.iSeries.iDB2DataAdapter"
      commandBuilderClass="IBM.Data.DB2.iSeries.iDB2CommandBuilder"
      usePositionalParameters="true"
      useParameterPrefixInSql="false"
      useParameterPrefixInParameter="false"
      parameterPrefix=""
      allowMARS="false"
/>
<provider
name="Informix"
      description="Informix NET Provider, 2.81.0.0"
      enabled="false"
      assemblyName="IBM.Data.Informix, Version=2.81.0.0, Culture=neutral, PublicKeyToken=7c307b91aa13d208"
      connectionClass="IBM.Data.Informix.IfxConnection"
      commandClass="IBM.Data.Informix.IfxCommand"
      parameterClass="IBM.Data.Informix.IfxParameter"
      parameterDbTypeClass="IBM.Data.Informix.IfxType"
      parameterDbTypeProperty="IfxType"
      dataAdapterClass="IBM.Data.Informix.IfxDataAdapter"
      commandBuilderClass="IBM.Data.Informix.IfxCommandBuilder"
      usePositionalParameters = "true"
      useParameterPrefixInSql = "false"
      useParameterPrefixInParameter = "false"
      useDeriveParameters="false"
      allowMARS="false"
/>
</providers>      

2.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>

        <!--/是否使用Satement命名空间,这里的命名空间指的是映射文件中sqlMap节点的namespace属性,默认是false-->

        <setting useStatementNamespaces="false"/>

        <!--是否启用DataMapper的缓存机制,针对全部的SqlMap,默认是true-->

        <setting cacheModelsEnabled="true"/>

        <!--是否启用SqlMapConfig.xsd schema验证映射文件,默认是false-->

        <setting validateSqlMap="false"/>

    </settings>

    <!--配置数据驱动提供类配置文件的路径和文件名-->

    <providers resource="providers.config"/>

    <!--如果在providers.config文件中指定了默认的数据库驱动,那么provider节点就不需要设置了,它的作用是在换数据库驱动时不需要修改providers.config文件。datasource节点用于指定ADO.NET Connection String.-->

    <database>

        <provider name="sqlServer2.0"/>

        <dataSource name="mydb" connectionString="data source=127.0.0.1;database=MyBatisDB;user id=sa;password=sa;"/>

    </database>

    <!--指定映射的文件的位置-->

    <sqlMaps>

        <sqlMap resource="Maps/PeopleMap.xml"/>

    </sqlMaps>

</sqlMapConfig>

3.每个实体类(表)都有一个单独的配置文件类,类型为xml。

代码生成器

也是生成这个类的,这样一来,用户就可以几秒钟创建开发一个iBatis项目了,实体类的配置文件格式如下,在网站的根目录创建一个Map的文件夹,新建xxxMap.xml格式的配置类,比如:PeopleMap.xml文件,示例代码如下:

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

<!--namespace必须用否者就报错(读取配置文件报:未将对象引用设置到对象的实例)-->

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

    <statements>

        <select id="GetPeopleById" parameterClass="string" resultClass="HashTable">

            SELECT * FROM People WHERE Id=#Id#

        </select>

        <insert id="Add" parameterClass="hashtable">

            INSERT  dbo.People (name ,age)

            VALUES  (#Name# , #Age#)

        </insert>

        <delete id="Delete" parameterClass="int" restultClass="int">

            DELETE FROM dbo.People WHERE Id=#Id#

        </delete>

        <update id="Update" parameterClass="hashtable" restltClass="int">

            UPDATE People SET name=#Name# WHERE Id=#Id#

        </update>

        <select id="GetAll" resultClass="HashTable">

            SELECT * FROM People

    </statements>

</sqlMap>

这三类配置文件必须都要有,与其他orm框架不同的是,web.config什么也不用配置,及时练数据库连接字符串也不是在它的文件中配置的,也就是web.config是没有被用到的。

第四步:iBatis框架语法与使用。

使用之前先来加入一个DB辅助类IBatisHepler.cs,代码如下:

iBatis for net 框架使用
iBatis for net 框架使用

IBatisHepler.cs

using System;
using System.Collections.Generic;
using System.Text;
using IBatisNet.DataMapper.Configuration.Statements;
using IBatisNet.DataMapper;
using IBatisNet.DataMapper.MappedStatements;
using IBatisNet.Common;
using IBatisNet.DataMapper.Scope;
using System.Data;
using IBatisNet.DataMapper.Configuration;
using System.Collections;


/// <summary>
/// IBatis 使用工具类
/// </summary>
public class IBatisHepler
{
private static ISqlMapper mapper = null;
static IBatisHepler()
    {
        DomSqlMapBuilder builder = new DomSqlMapBuilder();//其作用是根据配置文件创建SqlMap实例。
        mapper = builder.Configure("SqlMap.config") as SqlMapper;//SqlMapper是iBatisNet的核心组件,提供数据库操作的基础平台。SqlMapper可通过DomSqlMapBuilder创建。
    }
/// <summary>
/// 执行添加操作
/// </summary>
/// <param name="tag">语句ID</param>
/// <param name="paramObject">语句所需要的参数</param>
/// <returns>添加的主键</returns>
    public static object ExcuteInsert(string tag, Hashtable paramObject)
    {
return mapper.Insert(tag, paramObject);
    }
/// <summary>
/// 执行删除操作
/// </summary>
/// <param name="tag">语句ID</param>
/// <param name="paramObject">语句所需要的参数</param>
/// <returns>影响行数</returns>
    public static int ExcuteDelete(string tag, object paramObject)
    {
return mapper.Delete(tag, paramObject);
    }
/// <summary>
/// 执行修改操作
/// </summary>
/// <param name="tag">语句ID</param>
/// <param name="paramObject">语句所需要的参数</param>
/// <returns>影响行数</returns>
    public static int ExcuteUpdate(string tag, Hashtable paramObject)
    {
return mapper.Update(tag, paramObject);
    }
/// <summary>
/// 查询单个实体对象
/// </summary>
/// <param name="tag">语句ID</param>
/// <param name="paramObject">语句所需要的参数</param>
/// <returns>得到的Object</returns>
    public static object ExcuteSelectObj(string tag, object paramObject)
    {
object obj = mapper.QueryForObject(tag, paramObject);
return obj;
    }
/// <summary>
/// 分页查询
/// </summary>
/// <param name="tag">语句ID</param>
/// <param name="paramObject">语句所需要的参数</param>
/// <param name="pageIndex">页索引</param>
/// <param name="pageSize">每页显示的记录数</param>
/// <returns>得到的List集合</returns>
    public static IList ExcuteSelect(string tag, object paramObject, int pageIndex, int pageSize)
    {
return mapper.QueryForList(tag, paramObject, pageIndex, pageSize);
    }
/// <summary>
/// 通用的以DataTable的方式得到Select的结果(xml文件中参数要使用$标记的占位参数)
/// </summary>
/// <param name="tag">语句ID</param>
/// <param name="paramObject">语句所需要的参数</param>
/// <returns>得到的DataTable</returns>
    public static DataTable ExcuteSelect(string tag, object paramObject)
    {
        DataSet ds = new DataSet();
bool isSessionLocal = false;
        ISqlMapSession session = mapper.LocalSession;
if (session == null)
        {
            session = mapper.CreateSqlMapSession();
            session.OpenConnection();
            isSessionLocal = true;
        }
try
        {
            IDbCommand cmd = session.CreateCommand(CommandType.Text);
            cmd.Connection = session.Connection;
            cmd.CommandText = GetSql(tag, paramObject);
            IDbDataAdapter adapter = session.CreateDataAdapter(cmd);
            adapter.Fill(ds);
        }
finally
        {
if (isSessionLocal)
            {
                session.CloseConnection();
            }
        }
return ds.Tables[0];
    }
/// <summary>
/// 得到参数化后的SQL
/// </summary>
/// <param name="tag">语句ID</param>
/// <param name="paramObject">语句所需要的参数</param>
/// <returns>sql语句</returns>
    protected static string GetSql(string tag, object paramObject)
    {
        IStatement statement = mapper.GetMappedStatement(tag).Statement;
        IMappedStatement mapStatement = mapper.GetMappedStatement(tag);
        ISqlMapSession session = mapper.CreateSqlMapSession();
        RequestScope request = statement.Sql.GetRequestScope(mapStatement, paramObject, session);
return request.PreparedStatement.PreparedSql;
    }
/// <summary>
/// 用于分页控件使用
/// </summary>
/// <param name="tag">语句ID</param>
/// <param name="paramObject">语句所需要的参数</param>
/// <param name="PageSize">每页显示数目</param>
/// <param name="curPage">当前页</param>
/// <param name="recCount">记录总数</param>
/// <returns>得到的DataTable</returns>
    public static DataTable ExcuteSelect(string tag, object paramObject, int PageSize, int curPage, out int recCount)
    {
        IDataReader dr = null;
bool isSessionLocal = false;
string sql = GetSql(tag, paramObject);
string strCount = "select count(*) " + sql.Substring(sql.ToLower().IndexOf("from"));
        IDalSession session = mapper.LocalSession;
        DataTable dt = new DataTable();
if (session == null)
        {
            session = mapper.CreateSqlMapSession();
            session.OpenConnection();
            isSessionLocal = true;
        }
try
        {
            IDbCommand cmdCount = session.CreateCommand(CommandType.Text);
            cmdCount.Connection = session.Connection;
            cmdCount.CommandText = strCount;
object count = cmdCount.ExecuteScalar();
            recCount = Convert.ToInt32(count);
            IDbCommand cmd = session.CreateCommand(CommandType.Text);
            cmd.Connection = session.Connection;
            cmd.CommandText = sql;
            dr = cmd.ExecuteReader();
            dt = Paging(dr, PageSize, curPage);
        }
finally
        {
if (isSessionLocal)
            {
                session.CloseConnection();
            }
        }
return dt;
    }

/**/
/// <summary>
/// 取回合适数量的数据
/// </summary>
/// <param name="dataReader"></param>
/// <param name="PageSize"></param>
/// <param name="curPage"></param>
/// <returns></returns>
    protected static DataTable Paging(IDataReader dataReader, int PageSize, int curPage)
    {
        DataTable dt;
        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 = new object[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);
            }
else if (iCount > PageSize * curPage)
            {
break;
            }
            iCount++; // 临时记录变量递增
        }
if (!dataReader.IsClosed)
        {
            dataReader.Close();
            dataReader.Dispose();
        }
return dt;
    }
}      

使用语法如下:

// 添加引用

using System.Collections;

using IBatisNet.DataMapper;

using IBatisNet.DataMapper.Configuration;

// 1.添加

Hashtable ht_add = new Hashtable();

ht_add["Name"] = "IBatis";  // [注意]大小写要和xxxMap.xml里保持一致

ht_add["Age"] = 2001;

IBatisHepler.ExcuteInsert("Add", ht_add);

// 2.修改

Hashtable ht_up = new Hashtable();

ht_up["Id"] = "1";

ht_up["Name"] = "IBatis";

ht_up["Age"] = 2001;

IBatisHepler.ExcuteUpdate("Update", ht_up);

// 3.删除

IBatisHepler.ExcuteDelete("Delete", 14);

// 4.查询

Repeater1.DataSource = IBatisHepler.ExcuteSelectObj("GetPeopleById", "1");

Repeater1.DataBind();

我对此框架的评价:配置文件有点多,用户需要去写东西比较多,调用查询不是很好用,尤其是条件查询很不方便。

代码下载:【①.

本Demo下载

Orm框架相关文章链接:

1.

NHibernate使用之详细图解

2.

iBatis for net 框架使用

3.

iBatis for Net 代码生成器(CodeHelper)附下载地址

4.

NBear简介与使用图解 

5.

SubSonic框架使用图解

6.

GentleNet使用之详细图解
iBatis for net 框架使用

如果本文对你有所帮助,请打赏——1元就足够感动我:)

iBatis for net 框架使用
iBatis for net 框架使用

联系邮箱:[email protected]

我的GitHub:

https://github.com/vipstone

关注公众号:

iBatis for net 框架使用

作者:

王磊

出处:

http://vipstone.cnblogs.com/

本文版权归作者和博客园共有,欢迎转载,请标明出处。