MyBatis.Net 学习手记

MyBatis.NET的前身为IBatis,是JAVA版MyBatis在.NET平台上的翻版,相对NHibernate、EntityFramework等重量级ORM框架而言,MyBatis.NET必须由开发人员手动写SQL,相对灵活性更大,更容易保证DB访问的性能,适用开发团队里有SQL熟手的场景。

下面是使用步骤:

1、到官网http://code.google.com/p/mybatisnet/ 下载相关dll和文档

Doc-DataAccess-1.9.2.zip
Doc-DataMapper-1.6.2.zip
IBatis.DataAccess.1.9.2.bin.zip
IBatis.DataMapper.1.6.2.bin.zip

一共有4个zip包

2、创建一个Web应用,参考下图添加程序集引用

3、修改web.config,主要是配置log4net,参考下面的内容:

<?xml version="1.0"?>
<configuration><configSections><sectionGroup name="iBATIS"><section name="logging" type="IBatisNet.Common.Logging.ConfigurationSectionHandler, IBatisNet.Common"/></sectionGroup><section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/></configSections><system.web><compilation debug="true" targetFramework="4.0"/></system.web><iBATIS><logging><logFactoryAdapter type="IBatisNet.Common.Logging.Impl.Log4NetLoggerFA, IBatisNet.Common.Logging.Log4Net"><arg key="configType" value="inline"/><arg key="showLogName" value="true"/><arg key="showDataTime" value="true"/><arg key="level" value="ALL"/><arg key="dateTimeFormat" value="yyyy/MM/dd HH:mm:ss:SSS"/></logFactoryAdapter></logging></iBATIS><log4net><!-- Define some output appenders --><appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"><param name="File" value="mybatis.log"/><param name="AppendToFile" value="true"/><param name="MaxSizeRollBackups" value="2"/><param name="MaximumFileSize" value="100KB"/><param name="RollingStyle" value="Size"/><param name="StaticLogFileName" value="true"/><layout type="log4net.Layout.PatternLayout"><param name="Header" value="[Header]\r\n"/><param name="Footer" value="[Footer]\r\n"/><param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n"/></layout></appender><appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"><layout type="log4net.Layout.PatternLayout"><param name="ConversionPattern" value="%d [%t] %-5p %c [%x] &lt;%X{auth}&gt; - %m%n"/></layout></appender><!-- Set root logger level to ERROR and its appenders --><root><level value="DEBUG"/><appender-ref ref="RollingLogFileAppender"/><appender-ref ref="ConsoleAppender"/></root><!-- Print only messages of level DEBUG or above in the packages --><logger name="IBatisNet.DataMapper.Configuration.Cache.CacheModel"><level value="DEBUG"/></logger><logger name="IBatisNet.DataMapper.Configuration.Statements.PreparedStatementFactory"><level value="DEBUG"/></logger><logger name="IBatisNet.DataMapper.LazyLoadList"><level value="DEBUG"/></logger><logger name="IBatisNet.DataAccess.DaoSession"><level value="DEBUG"/></logger><logger name="IBatisNet.DataMapper.SqlMapSession"><level value="DEBUG"/></logger><logger name="IBatisNet.Common.Transaction.TransactionScope"><level value="DEBUG"/></logger><logger name="IBatisNet.DataAccess.Configuration.DaoProxy"><level value="DEBUG"/></logger></log4net>
</configuration>

4、添加Providers.config

把从官方下载的压缩包解开,就能找到providers.config文件,里面定义了MyBatis.Net支持的各种数据库驱动,本例以oracle为例,把其它不用的db provider全删掉,只保留下oracleClient1.0,同时把enabled属性设置成true,参考下面这样:

<?xml version="1.0"?>
<providers xmlns="http://ibatis.apache.org/providers"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><clear/>    <!--Oracle Support--><providername="oracleClient1.0"description="Oracle, Microsoft provider V1.0.5000.0"enabled="true"assemblyName="System.Data.OracleClient, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" connectionClass="System.Data.OracleClient.OracleConnection"commandClass="System.Data.OracleClient.OracleCommand"parameterClass="System.Data.OracleClient.OracleParameter"parameterDbTypeClass="System.Data.OracleClient.OracleType"parameterDbTypeProperty="OracleType"dataAdapterClass="System.Data.OracleClient.OracleDataAdapter"commandBuilderClass="System.Data.OracleClient.OracleCommandBuilder"usePositionalParameters="false"useParameterPrefixInSql="true"useParameterPrefixInParameter="false"parameterPrefix=":"allowMARS="false"/>
</providers>

5、添加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"><settings><setting useStatementNamespaces="false"/><setting cacheModelsEnabled="true"/></settings><!--db provider配置文件路径--><providers resource="providers.config"/><!--db provider类型及连接串--><database><provider name="oracleClient1.0" /><dataSource name="oracle" connectionString="Data Source=ORCL;Persist Security Info=True;User ID=scott;Password=tiger;Unicode=True" /></database><!--db与Entity的映射文件--><sqlMaps><sqlMap resource="Maps/ProductMap.xml"/></sqlMaps></sqlMapConfig>

这个文件也复制到Web项目根目录下,它的作用主要是指定db连接串,告诉系统providers.config在哪? 以及db与entity的映射文件在哪?(映射文件后面会讲到,这里先不管)

6、在Oraccle中先建表Product以及Sequence,方便接下来测试

-- CREATE TABLE
CREATE TABLE PRODUCT
(PRODUCTID      NUMBER NOT NULL,PRODUCTNAME    VARCHAR2(100),PRODUCTCOMPANY VARCHAR2(100),SIGNDATE       DATE,UPDATEDATE     DATE
);
-- CREATE/RECREATE PRIMARY, UNIQUE AND FOREIGN KEY CONSTRAINTS 
ALTER TABLE PRODUCTADD CONSTRAINT PK_PRODUCT_ID PRIMARY KEY (PRODUCTID);-- CREATE SEQUENCE 
CREATE SEQUENCE SQ_PRODUCT
MINVALUE 1
MAXVALUE 9999999999999999999999999
START WITH 1
INCREMENT BY 1
CACHE 20;

7、创建Maps目录,并在该目录下,添加映射文件ProductMap.xml,内容如下:

<?xml version="1.0" encoding="utf-8" ?>
<sqlMap namespace="EntityModel" xmlns="http://ibatis.apache.org/mapping"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><alias><!--类的别名--><typeAlias alias="Product" type="Web.Product,Web"/></alias><resultMaps><!--Product类与db表的映射--><resultMap id="SelectAllResult" class="Product"><result property="ProductId" column="ProductId"/><result property="ProductName" column="ProductName"/><result property="ProductCompany" column="ProductCompany" /><result property="SignDate" column="SignDate"  /><result property="UpdateDate" column="UpdateDate" /></resultMap></resultMaps><statements><!--查询所有记录--><select id="SelectAllProduct" resultMap="SelectAllResult"><![CDATA[SELECT ProductId,ProductName,ProductCompany,SignDate,UpdateDate FROM Product]]></select><!--查询单条记录--><select id="SelectByProductId" parameterClass="int" resultMap="SelectAllResult" extends="SelectAllProduct"><![CDATA[ where ProductId = #value#  ]]></select><!--插入新记录--><insert id="InsertProduct" parameterClass="Product">    <!--oracle sequence的示例用法--><selectKey property="ProductId" type="pre" resultClass="int">select SQ_Product.nextval as ProductId from dual</selectKey><![CDATA[INSERT into Product(ProductId,ProductCompany,ProductName,SignDate,UpdateDate)VALUES(#ProductId#,#ProductCompany#, #ProductName# , #SignDate# , #UpdateDate#)]]></insert><!--更新单条记录--><update id="UpdateProduct" parameterClass="Product"><![CDATA[Update Product SET ProductName=#ProductName#,ProductCompany=#ProductCompany#,            SignDate=#SignDate#,UpdateDate=#UpdateDate#Where ProductId=#ProductId#]]></update><!--根据主键删除单条记录--><delete id="DeleteProductById" parameterClass="int"><![CDATA[Delete From Product Where ProductId=#value#]]></delete></statements></sqlMap>

它的作用就是指定各种sql,以及db表与entity的映射规则,注意下insert中Sequence的用法!

8、创建实体类Product 

using System;namespace Web
{public class Product{public int ProductId { get; set; }public string ProductName { get; set; }public string ProductCompany { get; set; }public DateTime SignDate { get; set; }public DateTime UpdateDate { get; set; }public Product() { }}
}

9、写一个通用的BaseDA类,对MyBatis.Net做些基本的封装

using IBatisNet.DataMapper;
using System.Collections.Generic;namespace Web
{public static class BaseDA{public static int Insert<T>(string statementName, T t){ISqlMapper iSqlMapper = Mapper.Instance();if (iSqlMapper != null){return (int)iSqlMapper.Insert(statementName, t);}return 0;}public static int Update<T>(string statementName, T t){ISqlMapper iSqlMapper = Mapper.Instance();if (iSqlMapper != null){return iSqlMapper.Update(statementName, t);}return 0;}public static int Delete(string statementName, int primaryKeyId){ISqlMapper iSqlMapper = Mapper.Instance();if (iSqlMapper != null){return iSqlMapper.Delete(statementName, primaryKeyId);}return 0;}public static T Get<T>(string statementName, int primaryKeyId) where T : class{ISqlMapper iSqlMapper = Mapper.Instance();if (iSqlMapper != null){return iSqlMapper.QueryForObject<T>(statementName, primaryKeyId);}return null;}public static IList<T> QueryForList<T>(string statementName, object parameterObject = null){ISqlMapper iSqlMapper = Mapper.Instance();if (iSqlMapper != null){return iSqlMapper.QueryForList<T>(statementName, parameterObject);}return null;}}
}

10、然后就可以在Default.aspx.cs上测试了,参考下面的代码:

using System;
using System.Web.UI;namespace Web
{public partial class Default : Page{protected void Page_Load(object sender, EventArgs e){//插入var insertProductId = BaseDA.Insert<Product>("InsertProduct", new Product(){ProductCompany = "INFOSKY",ProductName = "iGSA2",SignDate = DateTime.Now,UpdateDate = DateTime.Now});//查单条记录var model = BaseDA.Get<Product>("SelectByProductId", insertProductId);ShowProduct(model);Response.Write("<hr/>");//修改记录if (model != null){model.ProductName = (new Random().Next(0, 99999999)).ToString().PadLeft(10, '0');int updateResult = BaseDA.Update<Product>("UpdateProduct", model);Response.Write("update影响行数:" + updateResult + "<br/><hr/>");}//查列表var products = BaseDA.QueryForList<Product>("SelectAllProduct");foreach (var pro in products){ShowProduct(pro);}Response.Write("<hr/>");//删除记录int deleteResult = BaseDA.Delete("DeleteProductById", insertProductId);Response.Write("delete影响行数:" + deleteResult + "<br/><hr/>");}void ShowProduct(Product pro){if (pro == null) return;Response.Write(string.Format("{0}&nbsp;,&nbsp;{1}&nbsp;,&nbsp;{2}&nbsp;,&nbsp;{3}&nbsp;,&nbsp;{4}<br/>",pro.ProductId, pro.ProductName, pro.ProductCompany, pro.SignDate, pro.UpdateDate));}}
}

示例源码下载:源码附件

转载于:https://www.cnblogs.com/hornet/p/4197044.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/406572.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Python 使用 UTF-8 编码

From: http://blog.chenlb.com/2010/01/python-use-utf-8.html 一般我喜欢用 utf-8 编码&#xff0c;在 python 怎么使用呢&#xff1f; 1、在 python 源码文件中用 utf-8 文字。一般会报错&#xff0c;如下&#xff1a; File "F:\workspace\psh\src\test.py", line …

curl下载文件的命令

curl文件下载 curl将下载文件输出到stdout&#xff0c;将进度信息输出到stderr&#xff0c;不显示进度信息使用–silent 选项。1 . curl URL --silent 这条命令是将下载文件输出到终端&#xff0c;所有下载的数据都被写入到stdout。2 . curl URL --silent -O 使用选项 -O 将下载…

后台运行python程序 遇到缓冲区问题

From: http://www.iteye.com/topic/867446 环境&#xff1a;linux 一段执行时间很长的程序&#xff08;用python做hive客户端执行mapreduce&#xff09; 在linux后台执行&#xff0c;把结果输出到某文件&#xff1a; Python代码 python xxx.py > log.log& 遇到的问题…

[nodejs][html5][css3][js] 个人网站上线

各个功能详细代码 http://www.cnblogs.com/wangxinsheng/p/4263591.html 2015年1月31日 --- 虽然比较懒&#xff0c;但终于匆忙的弄了个个人网站上线&#xff0c;没有博客功能。。。只有些数据抓取&#xff0c;百度地图&#xff0c;视屏游戏功能。 可是heroku站点在国内的速度超…

各种URL生成方式的性能对比

在上一篇文章中我们列举了各种URL生成的方式&#xff0c;其中大致可以分为三类&#xff1a; 直接拼接字符串&#xff08;方法一及方法二&#xff09; 使用Route规则生成URL&#xff08;方法三&#xff09; 使用Lambda表达式生成URL&#xff08;方法四及方法五&#xff09; 我们…

element-ui中el-table的表头、内容样式

方式1&#xff1a; 直接在标签上添加上属性值&#xff1a; <el-table:header-cell-style"{background:#F3F4F7,color:#555}" ></el-table>方式2&#xff1a; 在method里面写上方法&#xff1a; rowClass({ row, rowIndex}) {console.log(rowIndex) //表…

python下设置urllib连接超时

From: http://blog.csdn.net/vah101/article/details/6175406 首先导入socket库 import socket 在开始连接前的代码中&#xff0c;再加入 socket.setdefaulttimeout(6) #6秒内没有打开web页面&#xff0c;就算超时 然后就可以开始连接了&#xff0c;比如 try: …

请移步到我的新浪博客

请移步到我的新浪博客http://blog.sina.com.cn/highlandcat转载于:https://blog.51cto.com/highlandcata/221449

疯狂喷气机

2/3D游戏&#xff1a;2D 辅助插件&#xff1a;原生 游戏制作难度系数&#xff1a;初级 游戏教程网址&#xff1a;http://www.raywenderlich.com/69392/make-game-like-jetpack-joyride-unity-2d-part-1 1、控制摄像机跟随人物移动 public GameObject targetObject; //目标对象p…

elementui表格-改变某一列的样式

cellStyle({ row, column, rowIndex, columnIndex }) {if (columnIndex 0) {// 指定列号return ‘padding:0‘} else {return ‘‘} },

正则表达式基础(一)

From: http://www.usidcbbs.com/read-htm-tid-1457.html Perl 中的正则表达式 正则表达式是 Perl 语言的一大特色&#xff0c;也是 Perl 程序中的一点难点&#xff0c;不过如果大家能够很好的掌握他&#xff0c;就可以轻易地用正则表达式来完成字符串处理的任务&#xff0…

CodeSmith--SchemaExplorer类结构详细介绍

CodeSmith----SchemaExplorer类结构详细介绍 CodeSmith与数据库的联系&#xff0c;在CodeSmith中自带一个程序集SchemaExplorer.dll&#xff0c;这个程序集中的类主要用于获取数据库中各种对象的结构。 <% Property Name"SourceTable" Type"SchemaExplorer.T…

vue element项目常见实现表格内部可编辑功能

目录 前言 正文 1.简单表格行内内部可编辑 2. 数据从后端取得表格行内可编辑 3.批量表格整体的可编辑 结语 前言 后台系统都是各种表格表单编辑&#xff0c;整理了下常见的几种实现表格编辑的方式&#xff0c;希望有用。使用框架&#xff1a;vueelement 表格行内内部可编辑 数…

tar

tar命令是Unix的一个shell命令&#xff0c;该命令可在为多个制定文件创建一个档案文件&#xff0c;也可以从一个档案文件中解压缩出文件。tar档案文件的扩展名为“.tar”。tar包中的文件并不是压缩文件&#xff0c;而是所有文件集合成的一个文件。 tar这个名字源自在磁带上备份…

Yii2.0 技巧总结

View部分 1. 使用ActiveField中的hint生成提示文字 <? $form->field($model, freightAddedFee)->textInput()->hint(大于0的整数) ?> 2. 文本框添加placeholder属性&#xff0c;其实这个本来就是html5带的属性。 <? $form->field($model, mobile, $inp…