基於C#的.Net下整合IBatis

来源:https://www.cnblogs.com/Mr-kevin/archive/2018/01/10/8259526.html
-Advertisement-
Play Games

一. 準備工作 1. 點擊此下載支持.Net4.0的 iBatis.Net,工程中引用release文件夾下的dll 最新版(目前已不再更新),有稍作修改使其支持.NET4.0 2. 點擊此可查看 iBatis.Net 的幫助文檔 3. 點擊此下載 iBatis in Action 的中文版電子書, ...


一. 準備工作

  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>     
View Code

  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>
View Code 

  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>
View Code

  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>
View Code

  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");
        }
    }
}
View Code

  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 = 4;
        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);
            }
        }
    }
}
View Code  

  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,0)+1  
            WHERE userCode=#userCode# AND password=#password#
    </update>
  </statements>

</sqlMap>
View Code

  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 == 0)
            {
                throw new Exception("用戶名或密碼錯誤!");
            }
            user = list[0];
            if (user.isLocked == 1)
            {
                throw new Exception("用戶已經鎖定,禁止該用戶登錄!");
            }
            ExecuteUpdate("User.updateForLogin", user);
            LoginLog log = new LoginLog();
            log.userCode = user.userCode;
            log.loginType = 'I';
            ExecuteInsert("LoginLog.insertLog", log);

        }
    }
}
View Code

 

三. 測試

  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();
}
View Code

  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();
        }
    }
}
View Code

  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;//保存當前用戶    
        }

    }
}
View Code

  

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Python 語音:與機器進行語音交流,讓機器明白你說什麼,這是人們長期以來夢寐以求的事情。 語音識別是一門交叉學科。近二十年來,語音識別技術取得顯著進步,開始從實驗室走向市場。人們預計,未來10年內,語音識別技術將進入工業、家電、通信、汽車電子、醫療、家庭服務、消費電子產品等各個領域。 語音識別... ...
  • Java在如今的發展趨勢而言,一直都是處於流行的原因自然也是隨之而存在的。 java的特點如下幾個方面: 1.簡單性 Java 實際上是一個 C++去掉了複雜性之後的簡化版。如果讀者沒有編程經驗,會發現 Java 並不難掌握, 而如果讀者有 C 語言或是 C++語言基礎,則會覺得 Java 更簡單, ...
  • 一、Wtform WTForms是一個支持多個web框架的form組件,主要用於對用戶請求數據進行驗證。 安裝: pip3 install wtform 用途: 1. 用戶登錄註冊 當用戶登錄時候,需要對用戶提交的用戶名和密碼進行多種格式校驗。如: 用戶不能為空;用戶長度必須大於6; 用戶不能為空; ...
  • 前幾天遇到一個約瑟夫環演算法的問題,因為當時時間緊,而且之前也沒接觸過這個演算法,也就沒有太深究。今天有時間想起來這個問題了,就研究了一下,寫了一段代碼,試了一下,結果應該是正確的,記錄一下,以後用的時候也好找。下麵一段摘自百度百科。 約瑟夫環(約瑟夫問題)是一個數學的應用問題:已知n個人(以編號1,2 ...
  • "回到目錄" 職責鏈模式 它是一種設計模塊,主要將操作流程與具體操作解耦,讓每個操作都可以設置自己的操作流程,這對於工作流應用是一個不錯的選擇! 下麵是官方標準的定義:責任鏈模式是一種設計模式。在責任鏈模式里,很多對象由每一個對象對其下家的引用而連接起來形成一條鏈。請求在這個鏈上傳遞,直到鏈上的某一 ...
  • 基於WebImage封裝圖片上傳工具類,支持縮略圖和水印及其簡單的配置。 ...
  • 最近在做一部分Pyhton代碼轉c#代碼的工作,以下案例親自都測試過,現整理出來希望對有幫助的同學提供參考: Python | C# ...
  • 命令(Command) 2018/1/10 19:06:35 命令可以約束代碼,還可以約束步驟邏輯。(事件的作用是發佈和傳播一些消息,對如何響應事件不做規定,每個接收者可以使用自己的行為來響應事件。也就是說事件不具有約束力) 命令系統的基本元素 ·命令(Command):實際上就是實現了IComma ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...