c#使用iBatisNet例子复习

//先建数据库
create database ibatis 
use ibatis
create table ibatis(
id int primary key,
name varchar(19),
date datetime
)
insert into ibatis values(1,'name1',getdate());
insert into ibatis values(2,'name2',getdate());


//在创建iBatisNet网站应用
//在NuGet中搜索IbatisNet,引入IbatisNet.Common.dll与  IbatisNet.DataMapper.dll
//ibatis有三个很配置文件,
//providers.config:指定数据库提供者,.Net版本等信息。
//xxxxx.xml:映射规则。
//SqlMap.config:大部分配置一般都在这里,如数据库连接等等。

/**Windows应用项目或者类库项目中,需要放在项目的/bin/debug/目录下。在Web应用程序中,需要放在应用程序根目录。当然,这也不是强制性的,也可以很灵活地配置**/

 public IList<PersonModel> GetList()
        {
            //ISqlMapper mapper = Mapper.Instance();
            DomSqlMapBuilder builder = new DomSqlMapBuilder();
            ISqlMapper mapper = builder.Configure(@"C:\Users\Administrator\Desktop\Ibatis.Net测试\Ibatis.Net测试\SqlMap.config");
            IList<PersonModel> ListPerson = mapper.QueryForList<PersonModel>("SelectAllPerson", null);  //这个"SelectAllPerson"就是xml映射文件的Id
            return ListPerson;
        }
     /**以上代码,就从指定的位置去加载了SqlMap.config。注意,虽然SqlMap.config是从指定的位置,但是要注意里面的resource引入的资源,还是从原来的默认目录开始找**/


----------------------------例子---------------------------------------

//providers文件,使用的是数据库sql server2008
<?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="sqlServer2008"
    enabled="true"
    default="true"
    description="Microsoft SQL Server, provider V4.0.0.0 in framework .NET V4.0"
    assemblyName="System.Data, Version=4.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"
    />
</providers>


//映射文件  *.xml
<?xml version="1.0" encoding="utf-8" ?>
<sqlMap namespace="iBatisNet" xmlns="http://ibatis.apache.org/mapping"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <!--
       <isEqual>  比较属性值和静态值或另一个属性值是否相等。 
       <isNotEqual>  比较属性值和静态值或另一个属性值是否不相等。 
       <isGreaterThan>  比较属性值是否大于静态值或另一个属性值。 
       <isGreaterEqual>  比较属性值是否大于等于静态值或另一个属性值。 
       <isLessThan>  比较属性值是否小于静态值或另一个属性值。 
       <isLessEqual>  比较属性值是否小于等于静态值或另一个属性值。
       <isPropertyAvailable> 检查是否存在该属性(存在parameter bean的属性)  
       <isNotPropertyAvailable>  检查是否不存在该属性(不存在parameter bean的属性) 
       <isNull>  检查属性是否为null 
       <isNotNull>  检查属性是否不为null 
       <isEmpty>  检查Collection.size()的值,属性的String或String.valueOf()值,是否为null或空(“”或size() < 1) 
       <isNotEmpty>  检查Collection.size()的值,属性的String或String.valueOf()值,是否不为null或不为空(“”或size() > 0) 
       <isParameterPresent>  检查是否存在参数对象(不为null) 
       <isNotParameterPresent>  例子:<isNotParameterPresent prepend=”AND”>EMPLOYEE_TYPE = ‘DEFAULT’</isNotParameterPresent> 
        -->

  <!-- resultClass 直接设置返回的类型 -->
  <!-- resultMap 通过映射设置返回类型 -->
  <!--![CDATA[]禁止转义字符-->
  <!--parameterClass传递的参数类型-->


  <statements>
    <select id="getIdModel" resultClass="iBatisNet.Model"  parameterClass="int">
      <![CDATA[select * from ibatis where id=#i#]]>
    </select>

    <select id="getAllModel" resultClass="iBatisNet.Model">
      <![CDATA[select * from ibatis]]>
    </select>

    <insert id="insertModel"  parameterClass="iBatisNet.Model">
      <![CDATA[INSERT INTO IBATIS VALUES(#id#,#name#,#date#)]]>
    </insert>

    <delete id="deleteModel" parameterClass="int">
      <![CDATA[delete from ibatis where id=#i#]]>
    </delete>

    <update id="updateModel" parameterClass="iBatisNet.Model">
      <![CDATA[update ibatis set namE=#name#,date=#date# from ibatis where id=#id#]]>
    </update>

  </statements >
  <statements>
    <!--动态查询-->
    <select id="getDynamic" resultClass="iBatisNet.Model" parameterClaa="iBatisNet.Model">
      <![CDATA[select * from ibatis]]>

      <!--dynamic 会自动去除第一个 prepend="and"中的内容-->
      <dynamic prepend="where">
        <!--判断参数id是否为null或"",不是则加上prepend的值与其内的语句-->
        <isNotEmpty property="id" prepend="and">
          <![CDATA[ id=#id#]]>
        </isNotEmpty>

        <isNotEmpty property="name" prepend="and">
          <![CDATA[name=#name#]]>
        </isNotEmpty>
      </dynamic>
    </select>

    <select id="getDynamicIterate" resultClass="iBatisNet.Model" parameterClass="iBatisNet.Model">
      <![CDATA[select * from ibatis]]>

      <dynamic prepend="where">
      <isNotEmpty property="id" prepend="and">
         <![CDATA[id in]]>
        <!--iterate表示执行集合-->
        <iterate open="(" close=")" property="ary" conjunction=",">
          <![CDATA[#ary[]#]]>
        </iterate>
      </isNotEmpty>
      </dynamic>
    </select>
  </statements>
</sqlMap>


//全局配置文件
<?xml version="1.0" encoding="utf-8"?>
<sqlMapConfig
  xmlns="http://ibatis.apache.org/dataMapper"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <!--<properties resource="../../../properties.config"/>这个东西是变量用的,这里以最简单的实现说明,因此注释-->

  <settings>
    <!--调用映射文件id是是否加上
    <sqlMap namespace="iBatisNet" xmlns="http://ibatis.apache.org/mapping"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        的命名空间
        -->
    <setting useStatementNamespaces="false"/>
  </settings>

  <!-- 设置 provider 文件的来源,这个文件一般直接使用 myBatisNet 提供的文件 -->
  <!--这里使用的 provider 需要在 providers.config 中设置为启用
  enabled="true"-->
  <providers resource="providers.config"/>

  <!--数据库连接字符串-->
  <database>
    <provider name="sqlServer2008"/>
    <dataSource name="iBatisNet" connectionString="Data Source=127.0.0.1;Initial Catalog=ibatis;User ID=sa;Password=1"/>
  </database>

  <!--指向映射文件-->
  <sqlMaps>
    <sqlMap resource="MapFile.xml" />
  </sqlMaps>

</sqlMapConfig>




//对象模型
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace iBatisNet
{
    public class Model
    {
        public int id { get; set; }

        public string name { get; set; }
        public DateTime date { get; set; }

        public int[] ary {get;set;}
    }
}

//程序执行的入口文件
using IBatisNet.DataMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace iBatisNet
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            int i=2;

            //动态查询
            List<Model> modelDs = (List<Model>)Dal.GetDynamic<Model>("getDynamic", new Model { id = 2,name="name2" });

            //传数组
            int[] ary = new int[]{1,2,3 };

            List<Model> modelIteraet = (List<Model>)Dal.GetDunamicIteraet<Model>("getDynamicIterate", new Model() { ary =new int[]{ 1,2} });
            //查所有
            //getAllModel与映射文件的<select id="getAllModel">对应
            List<Model> models = (List<Model>) Dal.GetAllModel<Model>("getAllModel");
            //根据id查数据
            Model model = Dal.GetModel<Model>("getIdModel", 2);
            //新增
            //Dal.Insert("insertModel", new Model() {id=4,name="name3",date=DateTime.Now });
            //删除
            //Dal.Delete("deleteModel",i=4);
            //修改
            Dal.Update("updateModel",new Model {id=3,name="newname3",date=DateTime.Now });
        }
    }
}

//index.aspc.cs文件调用的方法,方法名一一对应
using IBatisNet.DataMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace iBatisNet
{
    public  class Dal
    {
        public static ISqlMapper instance()
        {
            ISqlMapper mapper =Mapper.Instance();
            return  mapper;
        }

        internal static T GetModel<T>(string v1, int v2)
        {
            return instance().QueryForObject<T>(v1,v2);
        }

        internal static IList<T> GetAllModel<T>(string v, object parameterObject = null)
        {
            return instance().QueryForList<T >(v,parameterObject);
        }

        internal static IList<T> GetDunamicIteraet<T>(string v1, object v2)
        {
            return instance().QueryForList<T>(v1,v2);
        }

        internal static void Insert<T>(string v, T model)
        {
            instance().Insert(v, model);
        }

        internal static void Delete(string v1, int v2)
        {
            instance().Delete(v1,v2);
        }

        internal static IList<T> GetDynamic<T>(string v, T model)
        {
           return instance().QueryForList<T>(v,model);
        }

        internal static void Update<T>(string v, T model)
        {
            instance().Update(v, model);
        }
    }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis是一个开源的持久化框架,可以帮助我们将数据从数据库中读取出来,然后转换为Java对象,并将Java对象写入数据库中。 在C#使用MyBatis,需要先安装MyBatis.Net库,然后在项目中引用该库。接着,我们需要创建一个配置文件,用于配置MyBatis的数据库连接信息、SQL语句等。在配置文件中,我们需要指定一个别名,用于在程序中引用这个配置文件。 接下来,我们需要创建一个映射文件,用于将数据库中的数据映射为Java对象。在映射文件中,我们需要定义一个 resultMap,用于定义Java对象与数据库表之间的关系。我们还需要定义一个 SQL 语句,用于从数据库中读取数据,并将其转换为Java对象。 在程序中,我们需要创建一个 SqlSession 对象,用于执行SQL语句。我们可以通过SqlSession对象调用selectOne、selectList、update、delete等方法,来执行SQL语句,并将结果转换为Java对象或者操作数据库。 下面是一个简单的示例,展示了如何在C#使用MyBatis: 1. 安装MyBatis.Net库 在Visual Studio中,选择“工具”-“NuGet包管理器”-“程序包管理器控制台”,然后输入以下命令: ``` Install-Package MyBatisNet ``` 2. 创建配置文件 在项目中创建一个名为“SqlMapConfig.xml”的文件,用于配置数据库连接信息、SQL语句等。以下是一个示例配置文件: ``` xml <?xml version="1.0" encoding="utf-8" ?> <sqlMapConfig> <database> <provider name="SqlServer" connectionString="Data Source=localhost;Initial Catalog=mydatabase;User ID=myuser;Password=mypassword;" /> </database> <sqlMap> <map resource="MyMapper.xml"/> </sqlMap> </sqlMapConfig> ``` 其中,provider元素用于指定数据库类型和连接字符串,map元素用于指定映射文件路径。 3. 创建映射文件 在项目中创建一个名为“MyMapper.xml”的文件,用于将数据库中的数据映射为Java对象。以下是一个示例映射文件: ``` xml <?xml version="1.0" encoding="utf-8" ?> <sqlMap namespace="MyMapper"> <resultMap id="MyResultMap" class="MyClass"> <result property="id" column="id"/> <result property="name" column="name"/> </resultMap> <select id="selectById" resultMap="MyResultMap"> SELECT * FROM mytable WHERE id=#id# </select> </sqlMap> ``` 其中,resultMap元素用于定义Java对象与数据库表之间的关系,select元素用于定义SQL语句。 4. 在程序中使用MyBatis 在程序中,我们需要创建一个 SqlSession 对象,用于执行SQL语句。以下是一个示例代码: ``` csharp using IBatisNet.DataMapper; using IBatisNet.DataMapper.Configuration; using IBatisNet.DataMapper.Configuration.Files; // 创建配置文件 DomSqlMapBuilder builder = new DomSqlMapBuilder(); ISqlMapper sqlMapper = builder.Configure(@"SqlMapConfig.xml"); // 执行SQL语句 MyClass obj = sqlMapper.QueryForObject<MyClass>("MyMapper.selectById", new { id = 1 }); ``` 以上是一个简单的示例,展示了如何在C#使用MyBatis。实际上,MyBatis还有很多其他的用法和功能,需要我们在实际开发中去探索和使用

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值