一. 准备工作

  1. 点击此下载支持.Net4.0的 iBatis.Net,工程中引用release文件夹下的dll

    最新版(目前已不再更新),有稍作修改使其支持.NET4.0

  2. 点击此可查看 iBatis.Net 的帮助文档

  3. 点击此下载 iBatis in Action 的中文版电子书,作为参考

  4. 点击此可查看适用于.NET,基于 iBatis in Action 的中文翻译,作为参考

二. 相关代码文件介绍

  1. dao.config  dao支持配置

<?xml version="1.0" encoding="utf-8"?>
<daoConfig xmlns="http://ibatis.apache.org/dataAccess"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <providers resource="./config/ibatisNet/providers.config" /> <context id="SqlMapDao">
<properties embedded="psi.properties.config, psi"/> <database>
<provider name="MySql"/>
<dataSource name="psi" connectionString="${connectionString}" />
</database> <daoSessionHandler id="SqlMap">
<property name="resource" value="./config/ibatisNet/SqlMap.config"/>
</daoSessionHandler> <daoFactory>
<dao interface="psi.Persistence.MapperDao.Interfaces.IUserDao, psi"
implementation="psi.Persistence.MapperDao.Implementations.UserDao, psi"/>
</daoFactory>
</context> </daoConfig>

  2. 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.7.9.0"
enabled="true"
assemblyName="MySql.Data, Version=6.7.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>

 

  3. 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="true"/>
<setting cacheModelsEnabled="true"/>
<setting validateSqlMap="false"/>
</settings> <sqlMaps>
<sqlMap embedded="psi.Persistence.Maps.User.xml, psi"/>
</sqlMaps>
</sqlMapConfig>

  4. properties.config  数据库连接等对安全性有要求的配置

<?xml version="1.0" encoding="utf-8" ?>
<settings>
<!-- User application and configured property settings go here.-->
<!-- Example: <add key="settingName" value="settingValue"/> -->
<add
key="connectionString"
value="Host=localhost;UserName=root;Password=123456;Database=psi;Port=3306;" />
</settings>

  5. DaoConfigManager.cs  程序启动时调用 DaoConfigManager.Instance(); 进行初始化

using IBatisNet.DataAccess;
using IBatisNet.DataAccess.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace psi.Persistence
{
public class DaoConfigManager
{
private static IDaoManager daoManager = null; public static IDaoManager GetSqlMapDao()
{
return Instance();
} public static IDaoManager Instance()
{
if (daoManager == null)
{
lock (typeof(DaoManager))
{
if (daoManager == null) // double-check
{
InitDao();
}
}
}
return daoManager;
} protected static void InitDao()
{
DomDaoManagerBuilder builder = new DomDaoManagerBuilder();
builder.Configure(".//config//ibatisNet//dao.config");
daoManager = DaoManager.GetInstance("SqlMapDao");
}
}
}

  6. BaseSqlMapDao.cs  对SqlMap的Dao操作进行的封装

using IBatisNet.Common.Pagination;
using IBatisNet.DataAccess;
using IBatisNet.DataAccess.DaoSessionHandlers;
using IBatisNet.DataAccess.Exceptions;
using IBatisNet.DataAccess.Interfaces;
using IBatisNet.DataMapper;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace psi.Persistence.MapperDao
{
/// <summary>
/// Summary description for BaseSqlMapDao.
/// </summary>
public class BaseSqlMapDao : IDao
{
protected const int PAGE_SIZE = ;
protected SqlMapper sqlMapper = null; /// <summary>
/// Looks up the parent DaoManager, gets the local transaction
/// (which should be a SqlMapDaoTransaction) and returns the
/// SqlMap associated with this DAO.
/// </summary>
/// <returns>The SqlMap instance for this DAO.</returns>
protected SqlMapper GetLocalSqlMap()
{
if (sqlMapper == null)
{
DaoManager daoManager = (DaoManager)DaoManager.GetInstance(this);
SqlMapDaoSession sqlMapDaoSession = (SqlMapDaoSession)daoManager.LocalDaoSession;
sqlMapper = (SqlMapper)sqlMapDaoSession.SqlMap;
}
return sqlMapper;
} /// <summary>
/// Simple convenience method to wrap the SqlMap method of the same name.
/// Wraps the exception with a DataAccessException to isolate the SqlMap framework.
/// </summary>
/// <param name="statementName"></param>
/// <param name="parameterObject"></param>
/// <returns></returns>
protected IList<T> ExecuteQueryForList<T>(string statementName, object parameterObject)
{
SqlMapper sqlMap = GetLocalSqlMap();
try
{
return sqlMap.QueryForList<T>(statementName, parameterObject);
}
catch (Exception e)
{
throw new DataAccessException("Error executing query '" + statementName + "' for list. Cause: " + e.Message, e);
}
} /// <summary>
/// Simple convenience method to wrap the SqlMap method of the same name.
/// Wraps the exception with a DataAccessException to isolate the SqlMap framework.
/// </summary>
/// <param name="statementName"></param>
/// <param name="parameterObject"></param>
/// <param name="skipResults"></param>
/// <param name="maxResults"></param>
/// <returns></returns>
protected IList ExecuteQueryForList(string statementName, object parameterObject, int skipResults, int maxResults)
{
SqlMapper sqlMap = GetLocalSqlMap();
try
{
return sqlMap.QueryForList(statementName, parameterObject, skipResults, maxResults);
}
catch (Exception e)
{
throw new DataAccessException("Error executing query '" + statementName + "' for list. Cause: " + e.Message, e);
}
} /// <summary>
/// Simple convenience method to wrap the SqlMap method of the same name.
/// Wraps the exception with a DataAccessException to isolate the SqlMap framework.
/// </summary>
/// <param name="statementName"></param>
/// <param name="parameterObject"></param>
/// <param name="pageSize"></param>
/// <returns></returns>
protected IPaginatedList ExecuteQueryForPaginatedList(string statementName, object parameterObject, int pageSize)
{
SqlMapper sqlMap = GetLocalSqlMap();
try
{
return sqlMap.QueryForPaginatedList(statementName, parameterObject, pageSize);
}
catch (Exception e)
{
throw new DataAccessException("Error executing query '" + statementName + "' for paginated list. Cause: " + e.Message, e);
}
} /// <summary>
/// Simple convenience method to wrap the SqlMap method of the same name.
/// Wraps the exception with a DataAccessException to isolate the SqlMap framework.
/// </summary>
/// <param name="statementName"></param>
/// <param name="parameterObject"></param>
/// <returns></returns>
protected object ExecuteQueryForObject(string statementName, object parameterObject)
{
SqlMapper sqlMap = GetLocalSqlMap(); try
{
return sqlMap.QueryForObject(statementName, parameterObject);
}
catch (Exception e)
{
throw new DataAccessException("Error executing query '" + statementName + "' for object. Cause: " + e.Message, e);
}
} /// <summary>
/// Simple convenience method to wrap the SqlMap method of the same name.
/// Wraps the exception with a DataAccessException to isolate the SqlMap framework.
/// </summary>
/// <param name="statementName"></param>
/// <param name="parameterObject"></param>
/// <returns></returns>
protected int ExecuteUpdate(string statementName, object parameterObject)
{
SqlMapper sqlMap = GetLocalSqlMap(); try
{
return sqlMap.Update(statementName, parameterObject);
}
catch (Exception e)
{
throw new DataAccessException("Error executing query '" + statementName + "' for update. Cause: " + e.Message, e);
}
} protected int ExecuteDelete(string statementName, object parameterObject)
{
SqlMapper sqlMap = GetLocalSqlMap(); try
{
return sqlMap.Delete(statementName, parameterObject);
}
catch (Exception e)
{
throw new DataAccessException("Error executing query '" + statementName + "' for delete. Cause: " + e.Message, e);
}
} /// <summary>
/// Simple convenience method to wrap the SqlMap method of the same name.
/// Wraps the exception with a DataAccessException to isolate the SqlMap framework.
/// </summary>
/// <param name="statementName"></param>
/// <param name="parameterObject"></param>
/// <returns></returns>
protected object ExecuteInsert(string statementName, object parameterObject)
{
SqlMapper sqlMap = GetLocalSqlMap(); try
{
return sqlMap.Insert(statementName, parameterObject);
}
catch (Exception e)
{
throw new DataAccessException("Error executing query '" + statementName + "' for insert. Cause: " + e.Message, e);
}
}
}
}

  

  7. User.xml  Sql语句存放位置

<?xml version="1.0" encoding="UTF-8" ?>
<sqlMap namespace="User"
xmlns="http://ibatis.apache.org/mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > <resultMaps>
<resultMap id="user" class="psi.Domain.User">
<result property="guid" column="guid"/>
<result property="userCode" column="userCode"/>
<result property="userName" column="userName"/>
<result property="password" column="password"/>
<result property="isLocked" column="isLocked"/>
<result property="flagOnline" column="flagOnline"/>
<result property="lastLoginTime" column="lastLoginTime"/>
<result property="loginCounter" column="loginCounter"/>
<result property="createDate" column="createDate"/>
<result property="createBy" column="createBy"/>
<result property="updateDate" column="updateDate"/>
<result property="updateBy" column="updateBy"/>
</resultMap> </resultMaps> <statements>
<select id = "getForLogin" parameterClass = "psi.Domain.User" resultMap="user">
select * from tb_user WHERE userCode=#userCode# AND password=#password#
</select> <update id="updateForLogin" parameterClass = "psi.Domain.User">
update tb_user SET flagOnline='Y',lastLoginTime=NOW(),loginCounter=IFNULL(loginCounter,)+
WHERE userCode=#userCode# AND password=#password#
</update>
</statements> </sqlMap>

  8. UserDao  数据访问接口

using IBatisNet.DataMapper;
using psi.Common;
using psi.Domain;
using psi.Persistence.MapperDao.Interfaces;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text; namespace psi.Persistence.MapperDao.Implementations
{
public class UserDao : BaseSqlMapDao, IUserDao
{
public void Login(User user)
{
if (string.IsNullOrWhiteSpace(user.userCode))
{
throw new Exception("帐户不能为空!");
} IList<User> list = ExecuteQueryForList<User>("User.getForLogin", user);
if (list == null || list.Count == )
{
throw new Exception("用户名或密码错误!");
}
user = list[];
if (user.isLocked == )
{
throw new Exception("用户已经锁定,禁止该用户登录!");
}
ExecuteUpdate("User.updateForLogin", user);
LoginLog log = new LoginLog();
log.userCode = user.userCode;
log.loginType = 'I';
ExecuteInsert("LoginLog.insertLog", log); }
}
}

三. 测试

  1. 前端控制器代码

User user = new User();
user.userCode = userCode;
user.password = password;
try
{
_bllUser.BeginTransaction();
_bllUser.Login(user);
_bllUser.CommitTransaction();
}
catch
{
_bllUser.RollBackTransaction();
throw new Exception();
}

  2. bllBase  业务逻辑处理基类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using psi.Common;
using IBatisNet.DataAccess;
using psi.Persistence; /*************************************************************************
* 程序说明: 业务逻辑层基类
**************************************************************************/
namespace psi.Business
{
/// <summary>
/// 业务逻辑层基类
/// </summary>
public abstract class bllBase
{
private IDaoManager daoManager;
protected IDaoManager DaoManager { get { return this.daoManager; } } public bllBase(){
daoManager = DaoConfigManager.GetSqlMapDao();
} public void BeginTransaction()
{
if (!daoManager.IsDaoSessionStarted())
daoManager.BeginTransaction();
} public void CommitTransaction()
{
daoManager.CommitTransaction();
} public void RollBackTransaction()
{
daoManager.RollBackTransaction();
}
}
}

  3. bllUser  业务逻辑处理代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using psi.Common;
using System.Data;
using psi.Persistence.MapperDao.Interfaces;
using psi.Persistence;
using IBatisNet.DataAccess;
using psi.Persistence.MapperDao.Implementations;
using psi.Domain; /*************************************************************************
* 程序说明: 用户管理的业务逻辑层
**************************************************************************/
namespace psi.Business
{
/// <summary>
/// 用户管理的业务逻辑层
/// </summary>
public class bllUser : bllBase
{
private IUserDao userDao; public bllUser()
: base()
{
userDao = DaoManager[typeof(IUserDao)] as IUserDao;
} public static void ValidateLogin(string userID, string password)
{
if (userID.Trim() == "")
throw new Exception("用户编号不正确或不能为空!"); if (password.Trim() == "")
throw new Exception("密码不正确或不能为空!");
} public void Login(User user)
{
userDao.Login(user); //用户实例,登录成功
Loginer loginer = new Loginer();
loginer.UserCode = user.userCode;
loginer.UserName = user.userName;
loginer.LoginTime = DateTime.Now; Loginer.CurrentUser = loginer;//保存当前用户
} }
}

  

基于.Net下整合IBatis的更多相关文章

  1. 基于.Net下整合FastReport,实现条码标签批量打印

    一. 准备工作 1. 点击此下载支持.Net4.0的 FastReport ,安装后并破解 2. VS2012 工具箱中,新建选项卡,添加 %安装目录%\Framework 4.0\FastRepor ...

  2. 基于.Net下整合RestSharp,实现REST服务客户端

    一. 准备工作 1. 点击此访问 RestSharp 官网,可作参考 2. VS2012 中安装支持.Net4.0的最新版 RestSharp 插件 工具---NuGet程序包管理器---程序包管理器 ...

  3. 团队软件开发_基于windows下截屏软件关于NABC框架的特点

    经过我们小组数次的激烈讨论,就自己的能力和时间而言,我们小组的初步的计划是开发一款基于windows下的截图软件. 关于这个软件的功能,我们初步的想法如下: 1.能在windows下后台运行,有相应的 ...

  4. Spring2.5整合Ibatis入门级开发实例

      分类: SPRING IBATIS2010-11-22 20:19 1170人阅读 评论(0) 收藏 举报 ibatisspringstringpropertiesclassuser 最近一直在看 ...

  5. paip.环境配置整合 ibatis mybatis proxool

    paip.环境配置整合 ibatis mybatis proxool  索引: ///////////1.调用 ///////////////2. ibatis 主设置文件  com/mijie/ho ...

  6. 基于SourceTree 下的 Git Flow 模型

    基于SourceTree 下的 Git Flow 模型 1. sourceTree  是一个开源的git 图形管理工具,可下载mac版本,windows版本 2. Git Flow 是一套使用Git进 ...

  7. 基于SpringMVC下的Rest服务框架搭建【1、集成Swagger】

    基于SpringMVC下的Rest服务框架搭建[1.集成Swagger] 1.需求背景 SpringMVC本身就可以开发出基于rest风格的服务,通过简单的配置,即可快速开发出一个可供客户端调用的re ...

  8. Spring整合Ibatis

    Spring整合Ibatis javaibatisspring 所需jar清单           ibatis-2.*.jar    *为任意版本,下同,ibatis工作包           sp ...

  9. ubuntu下整合eclipse和javah生成jni头文件开发android的native程序

    0:前言: 这两天一直在研究用android的jni调用第三方库,上网搜方法,但是都是泛泛而谈,没有demo,经过我几番折磨,写了n多的helloword工程,总是不成功,工程名字也就由helloow ...

随机推荐

  1. Elasticsearch(9):使用Logstash-input-jdbc同步数据库中的数

    1.数据同步方式 全量同步与增量同步 全量同步是指全部将数据同步到es,通常是刚建立es,第一次同步时使用.增量同步是指将后续的更新.插入记录同步到es. 2.常用的一些ES同步方法 1). elas ...

  2. cnpm安装过程中提示optional install error: Package require os(darwin) not compatible with your platform(win32)解决方法

    运行cnpm install后,出现 虽然提示不适合Windows,但是问题好像是sass loader出问题的.所以只要执行下面命令即可: 方案一: cnpm rebuild node-sass # ...

  3. scrapy实战2,使用内置的xpath,re和css提取值

      以伯乐在线文章为爬取目标blog.jobbole.com,发现在"最新文章"选项中可看到所有文章   一般来说,可以用scrapy中自带的xpath或者css来提取数据,定义在 ...

  4. scrapy实战1,基础知识回顾和虚拟环境准备

        视频地址 https://coding.imooc.com/learn/list/92.html   一. 基础知识回顾     1. 正则表达式 1)贪婪匹配,非贪婪匹配 .*? 非贪婪 . ...

  5. JSP入门之自定义标签

    第二部分简单讲解:主要讲解el表达式,核心标签库.本章主要讲解:自定义标签库:404页面,505页面,错误页面配置方法 全部代码下载:链接 1.JSP自定义标签: 自定义标签是用户定义的JSP语言元素 ...

  6. BurpSuite系列----Extender模块(扩展器)

    一.简介 Burp在软件中提供了支持第三方拓展插件的功能,方便使用者编写自己的自定义插件或从插件商店中安装拓展插件.Burp扩展程序可以以多种方式支持自定义Burp的行为,例如:修改HTTP请求和响应 ...

  7. 网络基础 05_DHCP

    1 DHCP概述 DHCP (Dynamic Host Configuration Protocol)是一种动态的向Internet终端提供配置参数的协议.在终端提出申请之后,DHCP可以向终端提供I ...

  8. 安卓手机移动端Web开发调试之Chrome远程调试(Remote Debugging)

    一.让安卓打debug模式的apk包 二.将电脑中的chrome升级到最新版本,在chrome浏览器地址栏中输入chrome://inspect/#devices: 在智能手机还未普及时,移动设备的调 ...

  9. Javac词法分析

    参考:<深入分析Java Web>技术内幕 许令波 词法分析过程涉及到的主要类及相关的继承关系如下: 词法分析的接口为Lexer,默认实现类为Scanner,Scanner会逐个读取Jav ...

  10. Linux 操作系统常用的三种流012

    Linux 操作系统常用的三种流: 0 标准输入流 1 标准输出流 2 标准错误流 通常在写脚本启动程序,写log时候,会出现如下写法: nohup commod > log.txt 2> ...