MyBatis的框架。

Introduction

MyBatis本是apache的一个开源项目iBatis,2010年这个项目由 apache software foundation迁移到了google code,并且改名为Mybatis。iBATIS一词源于"internet"和"abatis"的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO)。此处省去概念性描述若干词,下面直接进入主题,记录我学习MyBatis的过程。。。

Content

  1. 准备工作

    要想在项目中使用MyBatis.Net(当然,现在只是学习阶段),就需要到它的官方网站http://www.mybatis.org 下载相应的dll,根据官方网站的链接可以下载到IBatis.DataAccess.1.9.2.bin.zip和IBatis.DataMapper.1.6.2.bin.zip两个压缩文件(如果英语还不错,可以直接下载官方的文档,官方提供了两个压缩包Doc-DataAccess-1.9.2.zip和Doc-DataMapper-1.6.2.zip),在这个压缩文件中包含了几乎我们需要的所有dll文件(如果使用MySQL等其它数据库,可能需要到数据库厂商网站下载相应的dll驱动),包含如下文件:

    Castle.DynamicProxy.dll

    IBatisNet.Common.dll

    IBatisNet.Common.Logging.Log4Net.dll

    IBatisNet.DataAccess.dll

    IBatisNet.DataMapper.dll

    log4net.dll

    同时MyBatis还提供了一些辅助文件,如IBatisNet.Common.Logging.Log4Net.xml、IBatisNet.Common.xml、IBatisNet.DataAccess.xml、log4net.xml及IBatisNet.DataMapper.xml,将这些文件拷贝到VS的相应目录就可以在编写代码时获得程序的API说明,这个位置就是你的.NET Framework的安装目录,比如系统盘是C盘,这个位置就是C:/WINDOWS/Microsoft.NET/Framework/v4.0.30319/zh-CN。除此之外,还有一些xsd文件,如provider.xsd、SqlMap.xsd及SqlMapConfig.xsd,这些文件都是对应的xml文件的验证文件,利用这些文件就可以在VS中编辑这些文件时获得智能感知,从而减少出错的机会。假设你的系统是安装在C盘,如果你使用的是VS2010,那么就把这些文件拷贝到C:/Program Files/Microsoft Visual Studio 10.0/Xml/Schemas;如果你使用的是VS2012,那么就拷贝到C:/Program Files/Microsoft Visual Studio 11/Xml/Schemas。

    准备好DLL文件后,接下来是配置文件,如:Providers.config,SqlMap.config。

    Providers.config文件

    该文件提供了常用数据库驱动程序清单(共19个),在IBatis.DataAccess.1.9.2.bin下可以找到,但为提供对sqlserver2008的驱动信息,可下载官方的demo并找到该节点,这里就以sqlserver2008为例:

  1. <provider
  2.     name="sqlServer2008"
  3.     enabled="true"
  4.     default="true"
  5.     description="Microsoft SQL Server, provider V4.0.0.0 in framework .NET V4.0"
  6.     assemblyName="System.Data, Version=4.0.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089"
  7.     connectionClass="System.Data.SqlClient.SqlConnection"
  8.     commandClass="System.Data.SqlClient.SqlCommand"
  9.     parameterClass="System.Data.SqlClient.SqlParameter"
  10.     parameterDbTypeClass="System.Data.SqlDbType"
  11.     parameterDbTypeProperty="SqlDbType"
  12.     dataAdapterClass="System.Data.SqlClient.SqlDataAdapter"
  13.     commandBuilderClass=" System.Data.SqlClient.SqlCommandBuilder"
  14.     usePositionalParameters = "false"
  15.     useParameterPrefixInSql = "true"
  16.     useParameterPrefixInParameter = "true"
  17.     parameterPrefix="@"
  18.     allowMARS="true"
  19.     />

    根据value可以很大致明白各字段的含义,这里只说明三个地方,enabled,default,parameterprefix,如果想启用某个数据库驱动,只需要将enabled设置为true,如果设置了多个数据库驱动,可以使用default设置默认启动,parameterPrefix表示参数化SQL语句中参数的前缀。

    SqlMap.config文件

    这是一个配置当前数据库信息及实体映射文件配置的文件,直接看配置:

  20. <?xml version="1.0" encoding="utf-8" ?>
  21. <sqlMapConfig xmlns="http://ibatis.apache.org/dataMapper"
  22. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  23.   <properties>
  24.     <property key="selectKey" value="select @@IDENTITY as value" />
  25.   </properties>
  26.   <providers resource="./providers.config"/>
  27.   <database>
  28.     <provider name="sqlServer2008" />
  29.     <dataSource name="DataSource" connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True"/>
  30.   </database>
  31.  
  32.   <sqlMaps>
  33.     <sqlMap embedded="products.xml,FeihonSamples"/>
  34.   </sqlMaps>
  35. </sqlMapConfig>

    看到这里,需要注意两个地方:

  • Property key:当你向有自增长列的表插入数据时,需要用到这个属性。
  • 引用外部文件时可以使用resource(如: <providers resource="./providers.config"/>)和embedded(如:<sqlMap embedded="products.xml,FeihonSamples"/>)

    区别:resource直接引用外部文件,embedded需要将文件改为嵌入式资源,如下图:

    使用resouce时需要选择将文件Copy to Output Directory

  1. 编写映射文件

    映射文件与Nhibernate类似,主要包含两个部分:属性的映射和sql map,先通过代码直观感觉一下。

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <sqlMap namespace="Products" xmlns="http://ibatis.apache.org/mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  3.   <alias>
  4.     <typeAlias alias="Products" type="FeihonSamples.Products,FeihonSamples"></typeAlias>
  5.   </alias>
  6.   <resultMaps>
  7.     <resultMap id="SelectAllResult" class="Products">
  8.       <result property="ProductId" column="ProductID" dbType="int" type="int"/>
  9.       <result property="ProductName" column="ProductName" dbType="varchar" type="String"/>
  10.       <result property="SupplierId" column="SupplierID" dbType="int" type="int"/>
  11.       <result property="CategoryId" column="CategoryID" dbType="int" type="int"/>
  12.       <result property="QuantityPerUnit" column="QuantityPerUnit" dbType="nvarchar" type="string"/>
  13.       <result property="UnitPrice" column="UnitPrice" dbType="money" type="double"/>
  14.       <result property="UnitsInStock" column="UnitsInStock" dbType="smallint" type="int"/>
  15.       <result property="UnitsOnOrder" column="UnitsOnOrder" dbType="smallint" type="int"/>
  16.       <result property="ReorderLevel" column="ReorderLevel" dbType="smallint" type="int"/>
  17.       <result property="Discontinued" column="Discontinued" dbType="bit" type="bool"/>
  18.     </resultMap>
  19.   </resultMaps>
  20.  
  21.   <statements>
  22.     <select id="SelectAllProducts" resultMap="SelectAllResult">
  23.       <![CDATA[
  24.       select * from products
  25.       ]]>
  26.     </select>
  27.     <select id="SelectByProductId" parameterClass="int" resultMap="SelectAllResult" extends="SelectAllProducts">
  28.       <![CDATA[
  29.       where productid=#value#
  30.       ]]>
  31.     </select>
  32.     <select id="selectCount" resultClass="int">
  33.       <![CDATA[
  34.       select count(*) from products
  35.       ]]>
  36.     </select>
  37.  
  38.     <insert id="InsertProduct" parameterClass="Products">
  39.       <selectKey property="ProductId" type="post" resultClass="int">
  40.         ${selectKey}
  41.       </selectKey>
  42.       <![CDATA[
  43.       insert into Products
  44.       (ProductName
  45.            ,SupplierID
  46.            ,CategoryID
  47.            ,QuantityPerUnit
  48.            ,UnitPrice
  49.            ,UnitsInStock
  50.            ,UnitsOnOrder
  51.            ,ReorderLevel
  52.            ,Discontinued)
  53.        values
  54.        (#ProductName#
  55.            ,#SupplierId#
  56.            ,#CategoryId#
  57.            ,#QuantityPerUnit#
  58.            ,#UnitPrice#
  59.            ,#UnitsInStock#
  60.            ,#UnitsOnOrder#
  61.            ,#ReorderLevel#
  62.            ,#Discontinued#)
  63.       ]]>
  64.  
  65.     </insert>
  66.  
  67.     <delete id="DeleteProduct" parameterClass="int">
  68.       <![CDATA[
  69.       delete from products
  70.       where
  71.       productid=#productid#
  72.       ]]>
  73.     </delete>
  74.  
  75.   </statements>
  76. </sqlMap >

    映射文件是以XML文件的形式存在,这里先直观的感受一下,后续文章会对其中的属性做详细描述。

    1. 代码实现

      完整iBatis.Net的环境配置和引用后,就可以实现代码的调用了,还是通过直观的方式展现一下。

  77. using System;
  78. using System.Collections.Generic;
  79. using System.Linq;
  80. using System.Text;
  81. using System.Threading.Tasks;
  82. using IBatisNet.DataMapper;
  83. using IBatisNet.DataAccess;
  84. using IBatisNet.DataMapper.Configuration;
  85.  
  86. namespace FeihonSamples
  87. {
  88.     public class IbatisSample
  89.     {
  90.         private static SqlMapper mapper = null;
  91.         static IbatisSample()
  92.         {
  93.             DomSqlMapBuilder builder = new DomSqlMapBuilder();
  94.  
  95.             mapper = builder.Configure("SqlMap.config") as SqlMapper;
  96.         }
  97.  
  98.         public int Count()
  99.         {
  100.             int result = mapper.QueryForObject<int>("selectCount", null);
  101.             return result;
  102.         }
  103.  
  104.         public bool Create(Products product)
  105.         {
  106.             int id = (int)mapper.Insert("InsertProduct", product);
  107.             return id > 0;
  108.         }
  109.  
  110.         public Products Select(int productid)
  111.         {
  112.             Products product = mapper.QueryForObject<Products>("SelectByProductId", productid);
  113.             return product;
  114.         }
  115.  
  116.         public IList<Products> SelectAll()
  117.         {
  118.             var result = mapper.QueryForList<Products>("SelectByProductId", null);
  119.             return result;
  120.         }
  121.  
  122.         public bool Update(Products product)
  123.         {
  124.             var result = mapper.Update("DeleteProduct", product);
  125.             return result > 0;
  126.         }
  127.  
  128.         public bool Delete(Products product)
  129.         {
  130.             var result = mapper.Delete("DeleteProduct", product);
  131.             return result > 0;
  132.         }
  133.     }
  134. }

    简单说明:此处通过静态构造函数初始化Sqlmap.config,ibatis支持多用初始化方式,这里使用DOM的方式进行初始化,需要引用IBatisNet.DataMapper.Configuration;

Summary

虽然此文是初识MyBatis,但我还是使用一种最直观的方式先感受一下。

MyBatis最大的优点就是简单、灵活、易扩展,第一次使用就会让你喜欢上它。不过它也有它的缺点,映射文件需要更多的手工书写,当然也可以使用模板生成,如codesmith的ibatis模板等。

MyBatis For .NET学习- 初识MyBatis的更多相关文章

  1. (转)MyBatis框架的学习(七)——MyBatis逆向工程自动生成代码

    http://blog.csdn.net/yerenyuan_pku/article/details/71909325 什么是逆向工程 MyBatis的一个主要的特点就是需要程序员自己编写sql,那么 ...

  2. (转)MyBatis框架的学习(六)——MyBatis整合Spring

    http://blog.csdn.net/yerenyuan_pku/article/details/71904315 本文将手把手教你如何使用MyBatis整合Spring,这儿,我本人使用的MyB ...

  3. (转)MyBatis框架的学习(二)——MyBatis架构与入门

    http://blog.csdn.net/yerenyuan_pku/article/details/71699515 MyBatis框架的架构 MyBatis框架的架构如下图: 下面作简要概述: S ...

  4. mybatis源码学习--spring+mybatis注解方式为什么mybatis的dao接口不需要实现类

    相信大家在刚开始学习mybatis注解方式,或者spring+mybatis注解方式的时候,一定会有一个疑问,为什么mybatis的dao接口只需要一个接口,不需要实现类,就可以正常使用,笔者最开始的 ...

  5. 【mybatis源码学习】mybatis和spring框架整合,我们依赖的mapper的接口真相

    转载至:https://www.cnblogs.com/jpfss/p/7799806.html Mybatis MapperScannerConfigurer 自动扫描 将Mapper接口生成代理注 ...

  6. (转)MyBatis框架的学习(一)——MyBatis介绍

    http://blog.csdn.net/yerenyuan_pku/article/details/71699343 MyBatis介绍 MyBatis本是apache的一个开源项目iBatis,2 ...

  7. mybatis源码学习(二)--mybatis+spring源码学习

    这篇笔记主要来就,mybatis是如何利用spring的扩展点来实现和spring的整合 1.mybatis和spring整合之后,我们就不需要使用sqlSession.selectOne()这种方式 ...

  8. 【mybatis源码学习】mybatis的插件功能

    一.mybatis的插件功能可拦截的目标 org.apache.ibatis.executor.parameter.ParameterHandler org.apache.ibatis.executo ...

  9. 【mybatis源码学习】mybatis的结果映射

    一.mybatis结果映射的流程 二.mybatis结果映射重要的类 1.org.apache.ibatis.executor.resultset.ResultSetWrapper(对sql执行返回的 ...

随机推荐

  1. 请写出一段JavaScript代码,要求页面有一个按钮,点击按钮弹出确认框。程序可以判断出用

    请写出一段JavaScript代码,要求页面有一个按钮,点击按钮弹出确认框.程序可以判断出用 户点击的是“确认”还是“取消”. 解答: <HTML> <HEAD> <TI ...

  2. MemoryStream类读写内存

    和FileStream一样,MemoryStream和BufferedStream都派生自基类Stream,因此它们有很多共同的属性和方法,但是每一个类都有自己独特的用法.这两个类都是实现对内存进行数 ...

  3. 路由器port触发与转发---Port Forwarding &amp; Port Triggering

    What is Port Triggering? If you have not read my explanation of port forwarding do so now. You can f ...

  4. TypeScript 基本类型(一)

    1.boolean 布尔值 true/false let isDone: boolean = false; 2.number 数字:和JavaScript 一样,TypeScript 里的所有数字都是 ...

  5. 【BZOJ4378】[POI2015]Logistyka 树状数组

    [BZOJ4378][POI2015]Logistyka Description 维护一个长度为n的序列,一开始都是0,支持以下两种操作:1.U k a 将序列中第k个数修改为a.2.Z c s 在这 ...

  6. ios 统一设计,iOS6也玩扁平化

    转:http://esoftmobile.com/2014/01/14/build-ios6-ios7-apps/ 前言 前段时间,苹果在它的开发者网站上放出了iOS系统安装比例,其中iOS7占到78 ...

  7. MD5-【验签】

    MD5是什么? MD5是message-digest algorithm 5(信息-摘要算法)的缩写,被广泛用于加密和解密技术上,它可以说是文件的"数字指纹".任何一个文件,无论是 ...

  8. java工程编写manifest文件

    如果需要一个可以单独运行的jar包“Runnable JAR file”,省事的方法是妥妥的选择打一个可运行的jar包“Runnable JAR file”.如此一来,就可以把程序运行所依赖的类.第三 ...

  9. Request.RawUrl、Request.Url的区别

    如果访问的地址是: http://hovertree.com/guestbook/addmessage.aspx?key=hovertree%3C&n=myslider#zonemenu 那么 ...

  10. 理解Python的双下划线命名

    引子 我热情地邀请大家猜测下面这段程序的输出: class A(object):        def __init__(self):               self.__private()   ...