zoukankan      html  css  js  c++  java
  • MyBatis For .NET学习- 初识MyBatis

    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模板等。

     

  • 相关阅读:
    DFS+剪枝:N个蛋放入M个篮子并可以任意取
    笔试题:二叉树按层遍历&添加兄弟指针&求LCA&排序二叉树的查找
    Windows下部署BigBlueButton
    Gcc 下 MAX/MIN的安全宏定义
    Java NIO 笔记
    C++高效编程:内存与性能优化
    <<<EOT分界符怎么用?
    查询语句中不区分大小写和区分大小写及其模糊查询 的语句
    APPCAN本地打包时报有中文字符错误
    PHP中::、>、self、$this操作符的区别
  • 原文地址:https://www.cnblogs.com/long-gengyun/p/3346209.html
Copyright © 2011-2022 走看看