对于为什么要用ORM,为什么又要选择MyBatis.net,这个问题希望读者自行查找资料。这里直接贴出相关的调试笔记。

步骤1)下载与引用.

http://code.google.com/p/mybatisnet/

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

实际引用(请忽略ConfigLab.Comp):

步骤2)添加几个总的配置(暂时不涉及具体的实体及sql,只是一些总体的配置).

<web.config>

<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=301879
-->
<configuration>
<configSections> <!--这里是声明iBatis的、相关节点,否则无法读取!!!-->
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
<sectionGroup name="iBATIS">
<section name="logging" type="IBatisNet.Common.Logging.ConfigurationSectionHandler, IBatisNet.Common" />
</sectionGroup>
</configSections>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<!--
有关 web.config 更改的说明,请参见 http://go.microsoft.com/fwlink/?LinkId=235367。 可在 <httpRuntime> 标记上设置以下特性。
<system.Web>
<httpRuntime targetFramework="4.6.1" />
</system.Web>
-->
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime />
<pages controlRenderingCompatibilityVersion="4.0" />
</system.web>
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
<bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
</compilers>
</system.codedom>
<!--iBatis.net!!!-->
<common>
<logging>
<factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4net">
<arg key="configType" value="EXTERNAL" />
</factoryAdapter>
</logging>
</common>
<iBATIS>
<logging>
<logFactoryAdapter type="IBatisNet.Common.Logging.Impl.Log4NetLoggerFA, IBatisNet.Common.Logging.Log4Net">
<arg key="configType" value="external" />
</logFactoryAdapter>
</logging>
</iBATIS> </configuration>

<providers.config>

<?xml version="1.0" encoding="utf-8"?>
<providers
xmlns="http://ibatis.apache.org/providers"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <clear/>
<provider
name="MySql"
description="MySQL, MySQL provider 6.9.9.0"
enabled="true"
assemblyName="MySql.Data, Version=6.9.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" connectionClass="MySql.Data.MySqlClient.MySqlConnection"
commandClass="MySql.Data.MySqlClient.MySqlCommand"
parameterClass="MySql.Data.MySqlClient.MySqlParameter"
parameterDbTypeClass="MySql.Data.MySqlClient.MySqlDbType"
parameterDbTypeProperty="MySqlDbType"
dataAdapterClass="MySql.Data.MySqlClient.MySqlDataAdapter"
commandBuilderClass="MySql.Data.MySqlClient.MySqlCommandBuilder"
usePositionalParameters="false"
useParameterPrefixInSql="true"
useParameterPrefixInParameter="true"
parameterPrefix="?"
allowMARS="false"
/>
</providers>

<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 resource="../../../Files/properties.config"/>-->
<settings>
<setting useStatementNamespaces="true"/>
<!--<setting cacheModelsEnabled="true"/>-->
</settings> <providers resource="providers.config"/> <!-- Database connection information -->
<database>
<provider name="MySql"/>
<dataSource name="gameUser_SqlConnStr" connectionString="Database='gm_userdb';Data Source='localhost'; port='3306'; User Id='******';Password='********';charset='utf8';pooling=true;SslMode = none"/>
</database> <sqlMaps>
<sqlMap resource="mybatisLab/sqlmaps/cardtype.xml"/> <!--这里是我自己的相关目录-->
</sqlMaps> </sqlMapConfig>

[注]上面sqlMap中resource之所以是那个目录(mybatisLab/sqlmaps/cardtype.xml),是因为这里仅作为验证性的测试项目:

<log4Net.config>

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0, Culture=Neutral, PublicKeyToken=bf100aa01a5c2784" />
</configSections> <appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings> <log4net>
<appender name="IBatisLogFile" type="log4net.Appender.RollingFileAppender">
<file value="Logs\iBatis.log" />
<appendToFile value="true" />
<datePattern value="yyyy-MM-dd" />
<rollingStyle value="Date" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<header value="[Header] " />
<footer value="[Footer] " />
<conversionPattern value="%date{dd/MM/yyyy-HH:mm:ss} %m%newline%exception" />
</layout>
</appender> <appender name="IBatisMapperLogFile" type="log4net.Appender.RollingFileAppender">
<file value="Logs\iBatisMapper.log" />
<appendToFile value="true" />
<datePattern value="yyyy-MM-dd" />
<rollingStyle value="Date" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{dd/MM/yyyy-HH:mm:ss} %m%newline%exception" />
</layout>
</appender> <appender name="IBatisCacheLogFile" type="log4net.Appender.RollingFileAppender">
<file value="Logs\iBatisChache.log" />
<appendToFile value="true" />
<datePattern value="yyyy-MM-dd" />
<rollingStyle value="Date" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{dd/MM/yyyy-HH:mm:ss} %m%newline%exception" />
</layout>
</appender> <logger name="IBatisNet">
<level value="ALL"/>
<appender-ref ref="IBatisLogFile" />
</logger> <logger name="IBatisNet.DataMapper">
<level value="ALL"/>
<appender-ref ref="IBatisMapperLogFile" />
</logger>
</log4net>
</configuration>

步骤3)假设存在一个游戏卡类型的实体类.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IBatisNet.Common;
using IBatisNet.DataMapper; namespace ConfigLab.WebApiProject.mybatisLab.Entitys
{
/// <summary>
/// 功能简介:卡类型 (要么无手工添加的构造函数,要么需要存在一个无参构造函数)!!!
/// 博客:http://www.cnblogs.com/taohuadaozhu
/// </summary> public class CardType
{
public string CardTypeId { get; set; }
public string CardTypeName { get; set; } public DateTime CreateTime { get; set; } public int EnableStatus { get; set; } }
}

步骤4)添加一个对应的sql映射文件: cardtype.xml.

<?xml version="1.0" encoding="utf-8" ?>
<sqlMap namespace="CardType" xmlns="http://ibatis.apache.org/mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <alias>
<!--类的别名-->
<typeAlias alias="CardType" assembly="ConfigLab.WebApiProject.dll" type="ConfigLab.WebApiProject.mybatisLab.Entitys.CardType,ConfigLab.WebApiProject"/>
</alias> <resultMaps>
<!--CardType 类与db表的映射-->
<resultMap id="SelectAllResult" class="CardType">
<result property="CardTypeId" column="CardTypeId"/>
<result property="CardTypeName" column="CardTypeName"/>
<result property="CreateTime" column="CreateTime" />
<result property="EnableStatus" column="EnableStatus" />
</resultMap>
</resultMaps> <statements> <!--查询所有记录-->
<select id="SelectAllCardType" resultMap="SelectAllResult">
<![CDATA[SELECT CardTypeId,CardTypeName,CreateTime,EnableStatus FROM tb_cardtype]]>
</select> <!--查询单条记录-->
<select id="SelectByCardTypeId" parameterClass="string" resultMap="SelectAllResult" extends="SelectAllCardType">
<![CDATA[ where CardTypeId = #value# ]]>
</select> <!--插入新记录-->
<insert id="InsertProduct" parameterClass="CardType">
<!--如果是oracle,这样查询出最大序列号的示例用法-->
<!--
<selectKey property="ProductId" type="pre" resultClass="int">
select SQ_Product.nextval as ProductId from dual
</selectKey>
-->
<![CDATA[INSERT into tb_cardtype(CardTypeId,CardTypeName,CreateTime,EnableStatus)
VALUES(#CardTypeId#,#CardTypeName#,#CreateTime#,#EnableStatus#)]]>
</insert> <!--更新单条记录-->
<update id="UpdateCardTypeStatus" parameterClass="CardType">
<![CDATA[Update tb_cardtype SET EnableStatus=#EnableStatus#
Where CardTypeId=#CardTypeId#]]>
</update> <!--根据主键删除单条记录-->
<delete id="DeleteCardTypeId" parameterClass="string">
<![CDATA[Delete From tb_cardtype Where CardTypeId=#value#]]>
</delete> </statements> </sqlMap>

步骤5)添加一个封装基于MyBatis.net的数据访问工具类.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IBatisNet.DataMapper; namespace ConfigLab.LabCore.mybatisLab
{
/// <summary>
/// 功能简介:基于IBatis.net的数据访问操作处理类
/// </summary>
public static class BaseDAForIBatis
{
public static int Insert<T>(string statementName, T t)
{
ISqlMapper iSqlMapper = Mapper.Instance();
if (iSqlMapper != null)
{
return (int)iSqlMapper.Insert(statementName, t);
}
return ;
} public static int Update<T>(string statementName, T t)
{
ISqlMapper iSqlMapper = Mapper.Instance();
if (iSqlMapper != null)
{
return iSqlMapper.Update(statementName, t);
}
return ;
} public static int Delete(string statementName, int primaryKeyId)
{
ISqlMapper iSqlMapper = Mapper.Instance();
if (iSqlMapper != null)
{
return iSqlMapper.Delete(statementName, primaryKeyId);
}
return ;
} 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> GetForList<T>(string statementName, object parameterObject = null)
{ ISqlMapper iSqlMapper = Mapper.Instance();
if (iSqlMapper != null)
{
return iSqlMapper.QueryForList<T>(statementName, parameterObject);
}
return null;
}
}
}

步骤6)开始使用MyBatis.net(这个前身是iBatis框架).

using ConfigLab.LabCore.mybatisLab;
using ConfigLab.WebApiProject.mybatisLab.Entitys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http; namespace ConfigLab.WebApiProject.Controllers
{
/// <summary>
///博客:http://www.cnblogs.com/taohuadaozhu
/// </summary>
public class MyBatisController : ApiController
{
public IList<CardType> GetCardTypeList()
{
IList<CardType> listResult = BaseDAForIBatis.GetForList<CardType>("CardType.SelectAllCardType", null);
return listResult;
}
}
}

【经验总结】.

<1>sqlmaps/cardtype.xml
<typeAlias alias="CardType" assembly="ConfigLab.WebApiProject.dll" type="ConfigLab.WebApiProject.mybatisLab.Entitys.CardType,ConfigLab.WebApiProject"/>
注: type属性中逗号前是 命名空间.类, 逗号后面只是程序集本身的包名(如果命名空间很长,后面忽略)..相当于dll的名字去掉.dll
<2>
IList<CardType> listResult = BaseDAForIBatis.GetForList<CardType>("CardType.SelectAllCardType", null);
CardType.SelectAllCardType中的CardType是CardType.xml中根节点 namespace属性的值.
<3>
实体类中必须有一个无参构造函数,或者干脆不用手工添加构造函数(系统自动会处理).
<4>
需要引用一个Mysql.Data.dll (本例引用的是6.9.9.0版).
版本信息需要提供在providers.config中的Mysql驱动中.
enabled="true"需要打开.
<5>
SqlMap.config中的“ <database> <provider name="MySql"/>”节点中name属性,需要对应providers.config中provider的name属性.
<6>
相关的.config,.xml配置文件都要进行如下操作: 选中文件,右键属性,选择总是复制,内容。

关于对MyBatis.net框架的学习笔记( MyBatis.net是一款灵活性极大,sql由开发者自行在xml中编写, 轻量的ORM映射框架). 同时避免了sql硬编码到代码中不易维护的问题...的更多相关文章

  1. 试试 python-dotenv,避免敏感信息被硬编码到代码中

    我们开发的每个系统都离不开配置信息,例如数据库密码.Redis密码.邮件配置.各种第三方配置信息,这些信息都非常敏感,一旦泄露出去后果非常严重,被泄露的原因一般是程序员将配置信息和代码混在一起导致的. ...

  2. go微服务框架kratos学习笔记五(kratos 配置中心 paladin config sdk [断剑重铸之日,骑士归来之时])

    目录 go微服务框架kratos学习笔记五(kratos 配置中心 paladin config sdk [断剑重铸之日,骑士归来之时]) 静态配置 flag注入 在线热加载配置 远程配置中心 go微 ...

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

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

  4. Mina框架的学习笔记——Android客户端的实现

    Apache MINA(Multipurpose Infrastructure for Network Applications) 是 Apache 组织一个较新的项目,它为开发高性能和高可用性的网络 ...

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

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

  6. # go微服务框架kratos学习笔记六(kratos 服务发现 discovery)

    目录 go微服务框架kratos学习笔记六(kratos 服务发现 discovery) http api register 服务注册 fetch 获取实例 fetchs 批量获取实例 polls 批 ...

  7. go微服务框架kratos学习笔记七(kratos warden 负载均衡 balancer)

    目录 go微服务框架kratos学习笔记七(kratos warden 负载均衡 balancer) demo demo server demo client 池 dao service p2c ro ...

  8. go微服务框架kratos学习笔记九(kratos 全链路追踪 zipkin)

    目录 go微服务框架kratos学习笔记九(kratos 全链路追踪 zipkin) zipkin使用demo 数据持久化 go微服务框架kratos学习笔记九(kratos 全链路追踪 zipkin ...

  9. DBFlow框架的学习笔记之入门

    什么是DBFlow? dbflow是一款android高性的ORM数据库.可以使用在进行项目中有关数据库的操作.github下载源码 1.环境配置 先导入 apt plugin库到你的classpat ...

随机推荐

  1. PHP PDO连接

    连接是通过创建 PDO 基类的实例而建立的.不管使用哪种驱动程序,都是用 PDO 类名. 连接到 MySQL <?php高佣联盟 www.cgewang.com $dbh = new PDO(' ...

  2. PHP addAttribute() 函数

    实例 给根元素和 body 元素添加一个属性: <?php$note=<<<XML<note>高佣联盟 www.cgewang.com<to>Tove& ...

  3. dfs树

    dfs树是解决图中带环的利器. 前天CF的F题就是dfs树,但是当时我没有认真思考 觉着找到一个环过于困难 当时没有想到 也没理解dfs树的意义. 对于一张无向图求出一个dfs树 这个树有两种边 树边 ...

  4. ElasticSearch 基本概念 and 索引操作 and 文档操作 and 批量操作 and 结构化查询 and 过滤查询

    基本概念 索引: 类似于MySQL的表.索引的结构为全文搜索作准备,不存储原始的数据. 索引可以做分布式.每一个索引有一个或者多个分片 shard.每一个分片可以有多个副本 replica. 文档: ...

  5. 关于SqlServer那些事1(回归基础)

    即将实习,回归基础总结,希望可以再好好打磨一下基础的一些东西 关于如何在重新修改表结构时该变其权限设置 步骤: 点击工具 进入选项 设计器 取消勾选阻止保存要求重新创建表的更改 关于创建创建数据库以及 ...

  6. 一个C++版本的Sqlite3封装--SmartDb

    Sqlite是一个非常轻量级的开源数据库,在嵌入式系统中使用的比较多,存储管理数据非常方便,Sqlite库提供的基于C语言的API,用起来也挺简单,但是有一点不太好的就是API使用起来有些繁琐,另外就 ...

  7. 100例Python代码带你从入门到进阶!

    以下所有代码全都至少运行一遍,确保可复现.易于理解.逐步完成入门到进阶的学习. 此教程经过我 反复打磨多遍 ,经常为此熬夜,真心不易,文章比较长,看完有用,帮我点个在看或分享支持. 教程包括 62 个 ...

  8. 【av68676164(p48-p50】虚拟内存管理(1)

    7.3.1 页式虚拟内存管理概念 物理内存(即实内存)管理 特点 缺点 1 源程序直接使用内存的物理地址 程序间容易访问冲突 2 程序必须全部装入内存才能运行 内存太小程序无法运行 3 程序占用连续的 ...

  9. java_内部类、匿名内部类的使用

    内部类 将一个类A定义在另一个类B里面,里面的那个类A就称为内部类,B则称为外部类. 内部类的分类 成员内部类,类定义在了成员位置 (类中方法外称为成员位置) 局部内部类,类定义在方法内 成员内部类 ...

  10. Java中的引用与ThreadLocal

    Java中的引用--强软弱虚 强引用 Object object = new Object(),这个object就是一个强引用.如果一个对象具有强引用,那就类似于必不可少的生活用品,垃圾回收器绝不会回 ...