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. 哈希表类Hashtable

    哈希表是一种重要的存储方式,也是一种常见的检索方法.其基本思想是将关系码的值作为自变量,通过一定的函数关系计算出对应的函数值,把这个数值解释为结点的存储地址,将结点存入计算得到存储地址所对应的存储单元 ...

  2. centos7 禁用每次sudo 需要输入密码

    安装完centos7后,默认没有启用sudo,首先应该是对sudo进行设置.sudo的作用就是使当前非root用户在使用没有权限的命令 时,直接在命令前加入sudo,在输入自己当前用户的密码就可以完成 ...

  3. curl使用例子

    地址:http://phpbook.phpxy.com/34771 参考:http://php.net/manual/zh/function.curl-setopt.php 我们将curl的步骤分为以 ...

  4. uva414 - Machined Surfaces

    uva414 - Machined Surfaces /* 水题,值得一提的是,getline使用时注意不能让它多吃回车键,处理方法可以用getchar. */ #include <iostre ...

  5. 桥梁模式(Bridge)

    桥梁模式属于结构类的设计模式,示意结构图如下:

  6. 面试之Java持久层(十)

    91,什么是ORM?         对象关系映射(Object-Relational Mapping,简称ORM)是一种为了解决程序的面向对象模型与数据库的关系模型互不匹配问题的技术: 简单的说,O ...

  7. docker 从容器中拷文件到宿主机器中

    sudo docker cp 1d051604e0ea:/root/data /home/developer/zhanghui/data

  8. Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded.

    EF6进行Insert操作的时候提示错误 Store update, insert, or delete statement affected an unexpected number of rows ...

  9. centos6.5上搭建gitlab服务器(亲测可用哦)

    最近的版本控制中,git可谓是脱缰的野马,一发不可收拾.当然git的设计模式也是愈发的成熟,让人刮目相看,完美解决了svn上的不足之处.在目前分布式横行的天下,git可谓是占得了一席之地. 废话少说, ...

  10. 容器OOM相关

    使用容器的时候经常出现容器无缘无故重启的情况,首先我们要怀疑的应该是是否发生OOM了,通过以下命令可以查看 需要在容器的宿主机上在执行,宿主机上执行/var/log/dmesg有相关信息 dmesg ...