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
- 准备工作
要想在项目中使用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为例:
- <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"
- />
根据value可以很大致明白各字段的含义,这里只说明三个地方,enabled,default,parameterprefix,如果想启用某个数据库驱动,只需要将enabled设置为true,如果设置了多个数据库驱动,可以使用default设置默认启动,parameterPrefix表示参数化SQL语句中参数的前缀。
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">
- <properties>
- <property key="selectKey" value="select @@IDENTITY as value" />
- </properties>
- <providers resource="./providers.config"/>
- <database>
- <provider name="sqlServer2008" />
- <dataSource name="DataSource" connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True"/>
- </database>
- <sqlMaps>
- <sqlMap embedded="products.xml,FeihonSamples"/>
- </sqlMaps>
- </sqlMapConfig>
看到这里,需要注意两个地方:
- Property key:当你向有自增长列的表插入数据时,需要用到这个属性。
- 引用外部文件时可以使用resource(如: <providers resource="./providers.config"/>)和embedded(如:<sqlMap embedded="products.xml,FeihonSamples"/>)
区别:resource直接引用外部文件,embedded需要将文件改为嵌入式资源,如下图:
使用resouce时需要选择将文件Copy to Output Directory。
- 编写映射文件
映射文件与Nhibernate类似,主要包含两个部分:属性的映射和sql map,先通过代码直观感觉一下。
- <?xml version="1.0" encoding="utf-8" ?>
- <sqlMap namespace="Products" xmlns="http://ibatis.apache.org/mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
- <alias>
- <typeAlias alias="Products" type="FeihonSamples.Products,FeihonSamples"></typeAlias>
- </alias>
- <resultMaps>
- <resultMap id="SelectAllResult" class="Products">
- <result property="ProductId" column="ProductID" dbType="int" type="int"/>
- <result property="ProductName" column="ProductName" dbType="varchar" type="String"/>
- <result property="SupplierId" column="SupplierID" dbType="int" type="int"/>
- <result property="CategoryId" column="CategoryID" dbType="int" type="int"/>
- <result property="QuantityPerUnit" column="QuantityPerUnit" dbType="nvarchar" type="string"/>
- <result property="UnitPrice" column="UnitPrice" dbType="money" type="double"/>
- <result property="UnitsInStock" column="UnitsInStock" dbType="smallint" type="int"/>
- <result property="UnitsOnOrder" column="UnitsOnOrder" dbType="smallint" type="int"/>
- <result property="ReorderLevel" column="ReorderLevel" dbType="smallint" type="int"/>
- <result property="Discontinued" column="Discontinued" dbType="bit" type="bool"/>
- </resultMap>
- </resultMaps>
- <statements>
- <select id="SelectAllProducts" resultMap="SelectAllResult">
- <![CDATA[
- select * from products
- ]]>
- </select>
- <select id="SelectByProductId" parameterClass="int" resultMap="SelectAllResult" extends="SelectAllProducts">
- <![CDATA[
- where productid=#value#
- ]]>
- </select>
- <select id="selectCount" resultClass="int">
- <![CDATA[
- select count(*) from products
- ]]>
- </select>
- <insert id="InsertProduct" parameterClass="Products">
- <selectKey property="ProductId" type="post" resultClass="int">
- ${selectKey}
- </selectKey>
- <![CDATA[
- insert into Products
- (ProductName
- ,SupplierID
- ,CategoryID
- ,QuantityPerUnit
- ,UnitPrice
- ,UnitsInStock
- ,UnitsOnOrder
- ,ReorderLevel
- ,Discontinued)
- values
- (#ProductName#
- ,#SupplierId#
- ,#CategoryId#
- ,#QuantityPerUnit#
- ,#UnitPrice#
- ,#UnitsInStock#
- ,#UnitsOnOrder#
- ,#ReorderLevel#
- ,#Discontinued#)
- ]]>
- </insert>
- <delete id="DeleteProduct" parameterClass="int">
- <![CDATA[
- delete from products
- where
- productid=#productid#
- ]]>
- </delete>
- </statements>
- </sqlMap >
映射文件是以XML文件的形式存在,这里先直观的感受一下,后续文章会对其中的属性做详细描述。
- 代码实现
完整iBatis.Net的环境配置和引用后,就可以实现代码的调用了,还是通过直观的方式展现一下。
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using IBatisNet.DataMapper;
- using IBatisNet.DataAccess;
- using IBatisNet.DataMapper.Configuration;
- namespace FeihonSamples
- {
- public class IbatisSample
- {
- private static SqlMapper mapper = null;
- static IbatisSample()
- {
- DomSqlMapBuilder builder = new DomSqlMapBuilder();
- mapper = builder.Configure("SqlMap.config") as SqlMapper;
- }
- public int Count()
- {
- int result = mapper.QueryForObject<int>("selectCount", null);
- return result;
- }
- public bool Create(Products product)
- {
- int id = (int)mapper.Insert("InsertProduct", product);
- return id > 0;
- }
- public Products Select(int productid)
- {
- Products product = mapper.QueryForObject<Products>("SelectByProductId", productid);
- return product;
- }
- public IList<Products> SelectAll()
- {
- var result = mapper.QueryForList<Products>("SelectByProductId", null);
- return result;
- }
- public bool Update(Products product)
- {
- var result = mapper.Update("DeleteProduct", product);
- return result > 0;
- }
- public bool Delete(Products product)
- {
- var result = mapper.Delete("DeleteProduct", product);
- return result > 0;
- }
- }
- }
简单说明:此处通过静态构造函数初始化Sqlmap.config,ibatis支持多用初始化方式,这里使用DOM的方式进行初始化,需要引用IBatisNet.DataMapper.Configuration;
Summary
虽然此文是初识MyBatis,但我还是使用一种最直观的方式先感受一下。
MyBatis最大的优点就是简单、灵活、易扩展,第一次使用就会让你喜欢上它。不过它也有它的缺点,映射文件需要更多的手工书写,当然也可以使用模板生成,如codesmith的ibatis模板等。
MyBatis For .NET学习- 初识MyBatis的更多相关文章
- (转)MyBatis框架的学习(七)——MyBatis逆向工程自动生成代码
http://blog.csdn.net/yerenyuan_pku/article/details/71909325 什么是逆向工程 MyBatis的一个主要的特点就是需要程序员自己编写sql,那么 ...
- (转)MyBatis框架的学习(六)——MyBatis整合Spring
http://blog.csdn.net/yerenyuan_pku/article/details/71904315 本文将手把手教你如何使用MyBatis整合Spring,这儿,我本人使用的MyB ...
- (转)MyBatis框架的学习(二)——MyBatis架构与入门
http://blog.csdn.net/yerenyuan_pku/article/details/71699515 MyBatis框架的架构 MyBatis框架的架构如下图: 下面作简要概述: S ...
- mybatis源码学习--spring+mybatis注解方式为什么mybatis的dao接口不需要实现类
相信大家在刚开始学习mybatis注解方式,或者spring+mybatis注解方式的时候,一定会有一个疑问,为什么mybatis的dao接口只需要一个接口,不需要实现类,就可以正常使用,笔者最开始的 ...
- 【mybatis源码学习】mybatis和spring框架整合,我们依赖的mapper的接口真相
转载至:https://www.cnblogs.com/jpfss/p/7799806.html Mybatis MapperScannerConfigurer 自动扫描 将Mapper接口生成代理注 ...
- (转)MyBatis框架的学习(一)——MyBatis介绍
http://blog.csdn.net/yerenyuan_pku/article/details/71699343 MyBatis介绍 MyBatis本是apache的一个开源项目iBatis,2 ...
- mybatis源码学习(二)--mybatis+spring源码学习
这篇笔记主要来就,mybatis是如何利用spring的扩展点来实现和spring的整合 1.mybatis和spring整合之后,我们就不需要使用sqlSession.selectOne()这种方式 ...
- 【mybatis源码学习】mybatis的插件功能
一.mybatis的插件功能可拦截的目标 org.apache.ibatis.executor.parameter.ParameterHandler org.apache.ibatis.executo ...
- 【mybatis源码学习】mybatis的结果映射
一.mybatis结果映射的流程 二.mybatis结果映射重要的类 1.org.apache.ibatis.executor.resultset.ResultSetWrapper(对sql执行返回的 ...
随机推荐
- nginx中,$request_uri和$uri的区别
nginx中,$request_uri和$uri的区别 $request_uri This variable is equal to the *original* request URI as r ...
- GAN网络
http://www.sohu.com/a/130252639_473283 高分辨率图像重建 https://zhuanlan.zhihu.com/p/25201511 生成式对抗网络GAN有哪些最 ...
- HTML基本元素的运用
段落相关标签<p><br><hr> 格式化相关标签<small><sub><sup><pre> 列表相关标签< ...
- XML简单学习
XML简单概述 1.Extensible Markup language可扩展标记语言; 2.作用:具有层次性的描述有关系的数据: 体现在:描述数据关系:软件配置,以描述程序模块之间的关系: 语法介绍 ...
- tree的使用
//html <ul id="tree"></ul> js function initTree() { $('#tree').tree({ url: '/ ...
- 【Raspberry Pi】DHT11 温度湿度传感器数据读取
时序图参考厂家说明书:DHT11数字湿温度传感器的原理和应用范例 四个阵脚连接:VCC接3.3伏电源,Dout接GPIO口,我接的是物理12针脚,NC留空,GND接地. 波折1:电阻被错接进了VCC, ...
- 【python】模块测试 if name main
verbose=1 def listing(module): if verbose: print '-'*30 print 'name:',module.__name__,'file:',module ...
- 如何修改3D模型的原子属性
Chem3D是专门用于绘制化学三维模型和进行计算化学数据的ChemOffice组件,在三维模型中每个原子都有众多属性,比如原子类型.原子符号.原子编号以及原子颜色等等.掌握Chem 3D模型的原子属性 ...
- UML学习目录
用例图:http://www.cnblogs.com/yjjm/archive/2012/01/28/2385861.html http://kb.cnblogs.com/page/129491/
- 一次Tomcat6.0.33版本号与6.0.44版本号差异所引发的问题
前序(公司应用为Web应用, 部署serverLinux + Nginx + Tomcat ) 一天收到公司报警邮件,显示个别机器方法调用严重超时,寻常都是在100ms以内响应的方法,突然某段时间响应 ...