IBatis.net介绍

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配置

主要要用到的几个配置文件:

providers.config 这个直接拷贝到根目录,该文件定义各种数据库的驱动,包括SqlServer, Oracle, MySQL, PostgreSQL, DB2 and OLEDB, ODBC 等。

sqlmap.config 就是非常核心的一个配置文件,主要配置了数据库访问字符串,settings设置,以及配置实体类和数据库表相关xml。

还有一个database.config 文件,它是配置一些在sqlmap中用到得参数.

然后需要引入两个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">
 
  <!--<providers resource="database.config" />-->
  <settings>
    <setting useStatementNamespaces="true"/>
    <setting cacheModelsEnabled="true"/>
  </settings>
 
  <providers resource="providers.config" />
  <database>
    <!-- Optional ( default ) -->
    <provider name="sqlServer2.0"/>
    <dataSource name="iBatisNet" connectionString="Server=.; User ID=sa;Password=sa;Database=TestDB;Persist Security Info=True"/>
    </database>
  <sqlMaps>
    <sqlMap resource="Maps/Account.xml"/>
  </sqlMaps>
</sqlMapConfig>

useStatementNamespaces:是否启用命名空间

cacheModelsEnabled:是否缓存数据

<providers resource="providers.config" /> 引入数据库驱动文件

sqlMaps 节点就是配置一些sql语句以及实体映射的xml文件.

IBatis.net实战

现在让我们来做一个Demo

我用的是Sqlserver2005 ,新建一个数据表

在Vs2010下新建项目IBatisDemo

项目结构如下

IBatisDemo.Dao 提供一个统一的Mapper访问接口,

IBatisDemo.Model 数据实体

IBatisDemo.Service 数据操作

因为是做Demo没有对整体架构做过多的细节设置.

首先配置网站根目录下的Maps/Account.xml如下:

<?xml version="1.0" encoding="utf-8" ?>
<sqlMap namespace="Account" xmlns="http://ibatis.apache.org/mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <alias>
    <!-- alias:取别名
                    assembly:表示类所在的文件
                    type:表示该类的完整的名称
      -->
    <typeAlias alias="Account" assembly="IBatisDemo.Model.dll" type="IBatisDemo.Model.Accounts" />
  </alias>
 
  <resultMaps>
    <resultMap id="Account-result"  class="Account">
      <result property="Id"    column="id"/>
      <result property="Item"    column="Item"/>
      <result property="Year"    column="Year"/>
      <result property="Month"    column="Month"/>
      <result property="Day"    column="Day"/>
      <result property="CreateOn"    column="CreateOn"/>
      <result property="Level"    column="Level"/>
    </resultMap>
  </resultMaps>
 
  <statements>
    <select id="sql_selectByid" resultMap="Account-result">
      select * from Accounts
      <dynamic prepend="where">
        <isParameterPresent property="id" prepend="">
          [id] = #id#
        </isParameterPresent>
      </dynamic>
    </select>
 
    <select id="sql_selectAll" resultMap="Account-result">
      select * from Accounts
    </select>
 
    <insert id="sql_InsertOne" parameterClass="Account">
      insert into Accounts (Item,Money,Year,Month,Day,CreateOn,Level)
      values
      (#Item#,
      #Money#,
      #Year#,
      #Month#,
      #Day#,
      #CreateOn#,
      #Level#
      )
      <selectKey  type="post" resultClass="int" property="Id">
        SELECT CAST(@@IDENTITY as int) as Id
      </selectKey>
    </insert>
  </statements>
</sqlMap>

说明:

statements 节点:

在这些容器标签中有一些常用的属性如下所示

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 –>
<!-- 下面是sqlserver写法-->
    <selectKey  type="post" resultClass="int" property="Id">
      SELECT CAST(@@IDENTITY as int) as Id
    </selectKey>
<!-- 
    下面是针对Oracle的写法,Oracle没有autoincrement,而是用触发器实现的
    CURRVAL是在触发器中定义的
-->
<!--<insert id="insertRemark" parameterClass="RemarkInfo">
    insert into SGS_REMARK(REMARK) values(#remark#)
    <selectKey resultClass="int" keyProperty="id" > 
     SELECT S_SGS_REMARK.CURRVAL AS ID FROM DUAL 
    </selectKey> 
</insert>
-->
<!-- 下面是针对MySQL的写法 -->
<!-- 
    <selectKey resultClass="int" keyProperty="id" > 
    SELECT @@IDENTITY AS id 
    </selectKey> -->
 

Account.xml配置完成 .建实体类:

using System;
using System.Collections.Generic;
 
using System.Text;
 
namespace IBatisDemo.Model
{
    public class Accounts
    {
        public int Id { get; set; }
 
        public string Item { get; set; }
 
        public float Money { get; set; }
 
        public int Month { get; set; }
 
        public int Year { get; set; }
 
        public int Day { get; set; }
 
        public DateTime CreateOn { get; set; }
 
        public string Level { get; set; }
    }
}

Mapper.cs 获取Mapper的对象类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IBatisNet.DataMapper;
using IBatisNet.Common.Utilities;
using IBatisNet.DataMapper.Configuration;
 
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里面建立AccountService.cs 数据访问

using System;
using System.Collections.Generic;
 
using System.Text;
using System.Reflection;
using System.IO;
using IBatisDemo.Model;
using System.Data.SqlClient;
using IBatisDemo.Dao;
 
namespace IBatisDemo.Service
{
    public class AccountService
    {
        public int TestInsertOne(Accounts account)
        { 
            Object obj =Mapper.GetMaper.Insert("Account.sql_InsertOne", account);
            return (int)obj;
        }
 
        public Accounts GetAccount(int id)
        {
            return (Accounts)Mapper.GetMaper.QueryForObject("Account.sql_selectByid", id);
        }
 
        public IList<Accounts> GetAccountList() 
        {
            return Mapper.GetMaper.QueryForList<Accounts>("Account.sql_selectAll", null);
        }
    }
}

这里要注意命名空间.

在Default.aspx页面上调用Service

protected void Button1_Click(object sender, EventArgs e)
      {
          Accounts account = new Accounts();
          account.Id =-1;
          account.CreateOn = DateTime.Now;
          account.Day = 12;
          account.Item = "小刚1";
          account.Level = "无";
          account.Money = 56;
          account.Month = 6;
          account.Year = 2011;
 
          AccountService service = new AccountService();
          service.TestInsertOne(account);
      }
 
      protected void Button3_Click(object sender, EventArgs e)
      {
          AccountService service = new AccountService();
          IList<Accounts> accounts = service.GetAccountList();
 
          this.GridView1.DataSource = accounts;
          this.GridView1.DataBind();
      }
 
      protected void Button2_Click(object sender, EventArgs e)
      {
          AccountService service = new AccountService();
          Accounts account = service.GetAccount(2);
      }

运行效果:

IBatis.net介绍的更多相关文章

  1. iBatis简单介绍

    1.       Ibatis是开源软件组织Apache推出的一种轻量级的对象关系映射(ORM)框架,和Hibernate.Toplink等在java编程的对象持久化方面深受开发人员欢迎. 对象关系映 ...

  2. iBatis 简单介绍及基础入门

    iBATIS一词来源于“internet”和“abatis”的组合,是一个由Clinton Begin在2002年发起的开放源代码项目.于2010年6月16号被谷歌托管,改名为MyBatis.是一个基 ...

  3. ibatis实战之基础环境搭建

    关于ibatis的介绍.优缺点,以及ibatis和hibernate的比较再此不在赘述,可参阅其他资料. 一.准备工作 1.下载ibatis软件包http://download.csdn.net/de ...

  4. ibatis 入门

     iBatis 简单介绍: iBatis 是apache 的一个开源项目.一个O/R Mapping 解决方式,iBatis 最大的特点就是小巧.上手非常快.假设不须要太多复杂的功能.iBatis ...

  5. Ibatis的简单介绍

    定义: 相对Hibernate和Apache OJB 等“一站式”ORM解决方案而言,ibatis 是一种“半自动化”的ORM实现.以前ORM的框架(hibernate,ojb)的局限: 1. 系统的 ...

  6. 【ibatis】IBatis介绍

    Ⅰ .什么是Ibatis? ① iBATIS的是一个持久层框架,它能够自动在 Java, .NET, 和Ruby on Rails中与SQL数据库和对象之间的映射.映射是从应用程序逻辑封装在XML配置 ...

  7. [入门级] visual studio 2010 mvc4开发,用ibatis作为数据库访问媒介(一)

    [入门级] visual studio 2010 mvc4开发,用ibatis作为数据库访问媒介(一) Date  周二 06 一月 2015 By 钟谢伟 Tags mvc4 / asp.net 示 ...

  8. IBatis.Net项目数据库SqlServer迁移至Oracle经验

    最近完成了一个(IBatis.Net+MVC)项目的数据库+代码迁移工作,可把我折腾得~~~ IBatis.Net是一个ORM框架,具体介绍可以问度娘.我之前没用ORM框架使用经验,所以这一路我不是走 ...

  9. iBatis框架基本使用

    iBatis框架是Java持久层开发框架,说白了就是前人写了一部分代码(针对数据库操作),我们要做的就是再次开发,拿来框架直接使用. 我们自己开发时,dao层的sql语句都是写死在程序中的,如果查询条 ...

随机推荐

  1. 斯坦福iOS7公开课4-6笔记及演示Demo

    1.变量类型别滥用id,如果不仔细容易在程序执行时引发错误,因为在编译阶段编译器只是检测变量对象所属类型,尤其是类型为id时代表任何类型都可以通过检查,但不会检测变量对象调用的方法,这样当对象所属类不 ...

  2. 使用CocoaPods管理第三方开源类库

    iOS开发中经常会用到许多第三方开源类库,比如AFNetworking.FMDB.JSONKit等等,使用CocoaPods这个工具就能很方便得对工程中用到的类库进行管理,包括自动下载配置以及更新. ...

  3. Apache Shiro 简介

    使用 Apache Shiro 为 web 应用程序进行用户身份验证 Shiro 是一个 Apache Incubator 项目,旨在简化身份验证和授权.在本文中,了解 Apache Shiro 并通 ...

  4. 代码校验工具 SublimeLinter 的安装与使用

    SublimeLinter 是 Sublime 的插件,它的作用是检查代码语法是否有错误,并提示.习惯了 IDE 下写代码的人一定需要一款在 Sublime 上类似的语法检查工具.下面我们开始. 安装 ...

  5. IO流01--毕向东JAVA基础教程视频学习笔记

    提要 01 IO流(BufferedWriter)02 IO流(BufferedReader)03 IO流(通过缓冲区复制文本文件)04 IO流(readLine的原理)05 IO流(MyBuffer ...

  6. 【mysql】关于临时表

    mysql官方的介绍 In some cases, the server creates internal temporary tables while processing queries. Suc ...

  7. Linux Shell 02 流程控制语句

    一.if语句格式:支持if/elif/else形式,支持嵌套 1. command执行成功(及退出状态为0)时,执行command2 2. 当判断条件为test命令时,判断结果为true时,执行com ...

  8. 在ubuntu14.04上配置cuda_caffe_cudnn_anaconda_digits

    参考网上的很多网站,以这篇为主:http://blog.csdn.net/yhl_leo/article/details/50961542 这篇算是自己对caffe学习的一个总结系列的开头.首先因为c ...

  9. 华硕飞行堡垒zx50安装Ubunutu折腾记

    今年8月入手了华硕zx50,配置不错,作为一个合格的Linux爱好者,没买来一台电脑肯定得装上Linux编个程序什么的吧,,可恶的是,笔记本安装Linux系统往往比较麻烦,必须折腾很久才安装上,我手上 ...

  10. log4j日志优先级问题的后续

    前文:http://www.cnblogs.com/chyu/p/4280440.html 出现一处吐槽失误,当时还想怎么会设置成warn级别.. <appender name="ST ...