关于对MyBatis.net框架的学习笔记( MyBatis.net是一款灵活性极大,sql由开发者自行在xml中编写, 轻量的ORM映射框架). 同时避免了sql硬编码到代码中不易维护的问题...
对于为什么要用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=\"Web\" /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硬编码到代码中不易维护的问题...的更多相关文章
- 试试 python-dotenv,避免敏感信息被硬编码到代码中
我们开发的每个系统都离不开配置信息,例如数据库密码.Redis密码.邮件配置.各种第三方配置信息,这些信息都非常敏感,一旦泄露出去后果非常严重,被泄露的原因一般是程序员将配置信息和代码混在一起导致的. ...
- go微服务框架kratos学习笔记五(kratos 配置中心 paladin config sdk [断剑重铸之日,骑士归来之时])
目录 go微服务框架kratos学习笔记五(kratos 配置中心 paladin config sdk [断剑重铸之日,骑士归来之时]) 静态配置 flag注入 在线热加载配置 远程配置中心 go微 ...
- (转)MyBatis框架的学习(二)——MyBatis架构与入门
http://blog.csdn.net/yerenyuan_pku/article/details/71699515 MyBatis框架的架构 MyBatis框架的架构如下图: 下面作简要概述: S ...
- Mina框架的学习笔记——Android客户端的实现
Apache MINA(Multipurpose Infrastructure for Network Applications) 是 Apache 组织一个较新的项目,它为开发高性能和高可用性的网络 ...
- (转)MyBatis框架的学习(七)——MyBatis逆向工程自动生成代码
http://blog.csdn.net/yerenyuan_pku/article/details/71909325 什么是逆向工程 MyBatis的一个主要的特点就是需要程序员自己编写sql,那么 ...
- # go微服务框架kratos学习笔记六(kratos 服务发现 discovery)
目录 go微服务框架kratos学习笔记六(kratos 服务发现 discovery) http api register 服务注册 fetch 获取实例 fetchs 批量获取实例 polls 批 ...
- go微服务框架kratos学习笔记七(kratos warden 负载均衡 balancer)
目录 go微服务框架kratos学习笔记七(kratos warden 负载均衡 balancer) demo demo server demo client 池 dao service p2c ro ...
- go微服务框架kratos学习笔记九(kratos 全链路追踪 zipkin)
目录 go微服务框架kratos学习笔记九(kratos 全链路追踪 zipkin) zipkin使用demo 数据持久化 go微服务框架kratos学习笔记九(kratos 全链路追踪 zipkin ...
- DBFlow框架的学习笔记之入门
什么是DBFlow? dbflow是一款android高性的ORM数据库.可以使用在进行项目中有关数据库的操作.github下载源码 1.环境配置 先导入 apt plugin库到你的classpat ...
随机推荐
- webapp项目新建java class、webapp目录树结构
上一篇中我们介绍了IDEA.maven新建webapp项目的两种方式,分别是:在命令行中用模板创建.直接在IDEA中选择骨架创建. 但都存在一个问题:目录树不完整.有些人会不知道接下来该如何创建j ...
- demo3同通讯录展示的方式分组排序
按A-Z顺序分组展示 有些项目中会需要这样的需求.形成类似于上述的界面.类似于通讯录里边的排序.实现的效果:所有的数据展示的时候,能够分组展示.顺序按照A-Z的书序进行排列.如果不是以A-Z开头,则默 ...
- OAuth2.0-3客户端授权放到数据库
授权得客户端信息.授权码信息全都存在数据库 1.建表 官方给了个sql文件:https://github.com/spring-projects/spring-security-oauth/blob/ ...
- Qt数据库 QSqlTableModel实例操作(转)
本文介绍的是Qt数据库 QSqlTableModel实例操作,详细操作请先来看内容.与上篇内容衔接着,不顾本文也有关于上篇内容的链接. Qt数据库 QSqlTableModel实例操作是本文所介绍的内 ...
- 开源丨CloudBase CMS 内容管理系统!简单易用企业内容管理流
背景 云开发CloudBase CMS 是云开发推出的一站式云端内容管理系统,助力企业的数据运营管理工作. 开发者可以直接在云开发扩展能力中一键安装 CloudBase CMS,免费使用 CloudB ...
- NIO(三):Selector选择器
一.堵塞式与非堵塞式 在传统IO中,将数据由当前线程从客户端传入服务端,由服务端的内核进行判断传过来的数据是否合法,内核中是否存在数据. 如果不存在数据 ,并且数据并不合法,当前线程将会堵塞等待.当前 ...
- 曲线生成与求交—Bezier曲线
Bezier曲线生成 法国工程师Pierre Bezier在雷诺公司使用该方法来设计汽车.一条Bezier曲线可以拟合任何数目的控制点. 公式 设\(n+1\)个控制点\(P_0,P_1--P_n\) ...
- python爬虫:XPath语法和使用示例
python爬虫:XPath语法和使用示例 XPath(XML Path Language)是一门在XML文档中查找信息的语言,可以用来在XML文档中对元素和属性进行遍历. 选取节点 XPath使用路 ...
- 【Spring Security】1.快速入门
1 导入Spring Security的相关依赖 <dependency> <groupId>org.springframework.boot</groupId> ...
- C#LeetCode刷题之#485-最大连续1的个数(Max Consecutive Ones)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3714 访问. 给定一个二进制数组, 计算其中最大连续1的个数. ...