C#代码生成器-基于MyBatis.NET
程序员文章站
2022-03-15 18:57:32
...
C#代码生成器-基于MyBatis.NET
背景
编写代码生成器的目的是为了进一步减少程序员的重复性“体力劳动”,让程序员有更多的时间去做创造性的工作,提高编码的质量。我在编码和架构过程中层自己开发了一系列代码生成工具,本着开源和分享的目的,会在本期和后期博客中倾情奉献给有需要的朋友,不足指出也请多包含,因为共享源码,你也可以进行修改使用。
实现思路
预先编制模版,包括实体类、数据访问类、业务逻辑类、配置文件,基于已定义的数据库结构进行模版替换生成。
MyBatis.NET简介
MyBatis是业界非常优秀的ORM框架,可谓Java开发者必用的数据持久化框架。而MyBatis.NET其实就是使用C#对其进行翻版,可以让C#程序员用其简化数据访问的代码,从性能、轻量级、灵活度等角度看都比EntityFramework强不少,而且适合Java团队与C#团队的技术栈统一,便于不同语言的开发者转型。
关键模版代码
1、实体类模版(EntityClassTemplate.txt)
/************************************************************************************
* ${CopyRight}
* File:
* ${EntityClassName}.cs
* Description:
*
* Author:
* ${Author}
* ${AuthorEmail}
* ${Online}
* Finish DateTime:
* ${Date}
* History:
***********************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
namespace ${EntityNameSpace}
{
/// <summary>
/// 实体类${EntityClassName}
/// </summary>
[Serializable]
public class ${EntityClassName}
{
#region 私有字段
${PrivateFields}
#endregion
#region 公有属性
${PublicAttribute}
#endregion
}
}
2、Mapper映射文件模版(MapperTemplate.txt)
<?xml version="1.0" encoding="utf-8" ?>
<sqlMap namespace="${EntityClassName}"
xmlns="http://ibatis.apache.org/mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<alias>
<typeAlias alias="${EntityClassName}" type="${EntityNameSpace}.${EntityClassName}, ${EntityNameSpace}" />
</alias>
<parameterMaps>
<parameterMap id="MesnacPaggingParameters" class="map">
<parameter property="TableName" column="TableName" />
<parameter property="ReturnFields" column="ReturnFields" />
<parameter property="PageSize" column="PageSize" />
<parameter property="PageIndex" column="PageIndex" />
<parameter property="Where" column="Where" />
<parameter property="Orderfld" column="Orderfld" />
<parameter property="OrderType" column="OrderType" />
</parameterMap>
<parameterMap id="PagerShowParameters" class="map">
<parameter property="QueryStr" column="QueryStr" />
<parameter property="PageSize" column="PageSize" />
<parameter property="PageCurrent" column="PageCurrent" />
<parameter property="FdShow" column="FdShow" />
<parameter property="FdOrder" column="FdOrder" />
<parameter property="Rows" column="Rows" direction="Output"/>
</parameterMap>
</parameterMaps>
<resultMaps>
<!--分页结果映射,返回实体List数据 begin-->
<resultMap id="EntityResult" class="${EntityClassName}">
${PropertyMap}
</resultMap>
<resultMap id="PageEntityResult" class="map">
<result property="PageCount" column="PageCount" />
<result property="RecordCount" column="RecordCount" />
</resultMap>
<!--分页结果映射,返回实体List数据 end-->
<!--分页结果映射,返回DataSet数据 begin-->
<resultMap id="TableResult" class="Row">
${PropertyMap}
</resultMap>
<resultMap id="PageTableResult" class="Row">
<result property="PageCount" column="PageCount" />
<result property="RecordCount" column="RecordCount" />
</resultMap>
<!--分页结果映射,返回DataSet数据 end-->
</resultMaps>
<statements>
<procedure id="${EntityClassName}.GetPageDataMesnacPagging" parameterMap="MesnacPaggingParameters" resultMap="EntityResult,PageEntityResult">
MesnacPaging
</procedure>
<procedure id="${EntityClassName}.GetPageDataPagerShow" parameterMap="PagerShowParameters" resultMap="EntityResult">
PagerShow
</procedure>
<procedure id="${EntityClassName}.GetPageDataSet" parameterMap="MesnacPaggingParameters" resultMap="TableResult,PageTableResult">
MesnacPaging
</procedure>
<select id="${EntityClassName}.GetPageDataByReader" parameterMap="MesnacPaggingParameters">
SELECT
${FieldList}
FROM [dbo].[${EntityClassName}]
</select>
<select id="${EntityClassName}.GetRowCount" parameterClass="map" resultClass="int">
SELECT COUNT(*) FROM [dbo].[${EntityClassName}]
</select>
<select id="${EntityClassName}.GetRowCountByWhere" parameterClass="String" resultClass="int">
SELECT COUNT(*) FROM [dbo].[${EntityClassName}] WHERE 1 = 1 AND ($where$)
</select>
<select id="${EntityClassName}.GetById" parameterClass="map" resultClass="${EntityClassName}">
SELECT
${FieldList}
FROM [dbo].[${EntityClassName}] WHERE (${KeyValueList})
</select>
<select id="${EntityClassName}.GetListByWhere" parameterClass="map" resultClass="${EntityClassName}">
SELECT
${FieldList}
FROM [dbo].[${EntityClassName}]
${DynamicWhere}
</select>
<select id="${EntityClassName}.GetListByWhereStr" parameterClass="map" resultClass="${EntityClassName}">
SELECT
${FieldList}
FROM [dbo].[${EntityClassName}]
WHERE 1 = 1 AND ($where$)
</select>
<select id="${EntityClassName}.GetListByWhereAndOrder" parameterClass="map" resultClass="${EntityClassName}">
SELECT
${FieldList}
FROM [dbo].[${EntityClassName}]
${DynamicWhere}
<isPropertyAvailable property="OrderBy" prepend="">
order by $OrderBy$
</isPropertyAvailable>
</select>
<select id="${EntityClassName}.GetListByWhereAndOrderStr" parameterClass="map" resultClass="${EntityClassName}">
SELECT
${FieldList}
FROM [dbo].[${EntityClassName}]
WHERE 1 = 1 AND ($where$)
<isPropertyAvailable property="OrderBy" prepend="">
order by $OrderBy$
</isPropertyAvailable>
</select>
<select id="${EntityClassName}.GetDataSetByWhere" parameterClass="map" resultClass="Row">
SELECT
${FieldList}
FROM [dbo].[${EntityClassName}]
${DynamicWhere}
</select>
<select id="${EntityClassName}.GetDataSetByWhereStr" parameterClass="map" resultClass="Row">
SELECT
${FieldList}
FROM [dbo].[${EntityClassName}]
WHERE 1 = 1 AND ($where$)
</select>
<select id="${EntityClassName}.GetDataSetByFieldsAndParams" parameterClass="map" remapResults="true" resultClass="Row">
SELECT
$ColumnNames$
FROM [dbo].[${EntityClassName}]
${DynamicWhere}
</select>
<select id="${EntityClassName}.GetAllListOrder" parameterClass="map" resultClass="${EntityClassName}">
SELECT
${FieldList}
FROM [dbo].[${EntityClassName}]
<isPropertyAvailable property="OrderBy" prepend="">
order by $OrderBy$
</isPropertyAvailable>
</select>
<select id="${EntityClassName}.GetTopNListWhereOrder" parameterClass="map" resultClass="${EntityClassName}">
SELECT
<isPropertyAvailable property="Top" prepend="">
Top (#Top#)
</isPropertyAvailable>
${FieldList}
FROM [dbo].[${EntityClassName}]
${DynamicWhere}
<isPropertyAvailable property="OrderBy" prepend="">
order by $OrderBy$
</isPropertyAvailable>
</select>
<select id="${EntityClassName}.GetTopNListWhereOrderStr" parameterClass="map" resultClass="${EntityClassName}">
SELECT
<isPropertyAvailable property="Top" prepend="">
Top (#Top#)
</isPropertyAvailable>
${FieldList}
FROM [dbo].[${EntityClassName}]
WHERE 1 = 1 AND ($where$)
<isPropertyAvailable property="OrderBy" prepend="">
order by $OrderBy$
</isPropertyAvailable>
</select>
<select id="${EntityClassName}.GetMaxValueByProperty" parameterClass="map" resultClass="map">
SELECT max($ColumnName$) FROM [dbo].[${EntityClassName}]
${DynamicWhere}
</select>
<insert id="${EntityClassName}.Insert" parameterClass="${EntityClassName}" resultClass="Int32">
INSERT INTO [dbo].[${EntityClassName}] (
${FieldListNoIdentity}
) VALUES (
${ValueListNoIdentity}
)
SELECT @@IDENTITY
</insert>
<update id="${EntityClassName}.Update" parameterClass="${EntityClassName}">
UPDATE [dbo].[${EntityClassName}] SET
${FieldValueListNoKeyIdentity}
WHERE
(${KeyValueList})
SELECT @@rowcount
</update>
<update id="${EntityClassName}.UpdateFields" parameterClass="map">
UPDATE [dbo].[${EntityClassName}] SET
$FieldSetValue$
WHERE 1 = 1 AND ($where$)
SELECT @@rowcount
</update>
<delete id="${EntityClassName}.Delete" parameterClass="int32">
DELETE FROM [dbo].[${EntityClassName}]
WHERE
(${KeyValueList})
SELECT @@rowcount
</delete>
<delete id="${EntityClassName}.DeleteByEntity" parameterClass="${EntityClassName}">
DELETE FROM [dbo].[${EntityClassName}]
WHERE
(${KeyValueList})
SELECT @@rowcount
</delete>
<delete id="${EntityClassName}.DeleteByWhere" parameterClass="String">
DELETE FROM [dbo].[${EntityClassName}]
WHERE 1 = 1 AND ($where$)
SELECT @@rowcount
</delete>
<statement id="${EntityClassName}.ClearData">
truncate table [${EntityClassName}]
</statement>
</statements>
</sqlMap>
3、DBHelper模版(DBHelper.txt)
/************************************************************************************
* ${CopyRight}
* File:
* DBHelper.cs
* Description:
* SQL数据访问辅助类
* Author:
* ${Author}
* ${AuthorEmail}
* ${Online}
* Finish DateTime:
* ${Date}
* History:
*
***********************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using MyBatis.DataMapper;
using MyBatis.DataMapper.Configuration;
using MyBatis.DataMapper.Configuration.Interpreters.Config.Xml;
using MyBatis.DataMapper.Session;
using MyBatis.DataMapper.Session.Stores;
namespace ${DAONameSpace}
{
public delegate string KeyConvert(string key);
/// <summary>
/// 数据访问辅助类
/// </summary>
public class DbHelper : ScriptBase
{
#region 单例实现
private static DbHelper _instance = null;
private IConfigurationEngine _engine = null;
private ISessionFactory _sessionFactory = null;
private ISessionStore _sessionStore = null;
private IDataMapper _dataMapper = null;
private KeyConvert ConvertKey = null;
private DbHelper()
{
string resource = "SqlMap.config";
try
{
ConfigurationSetting configurationSetting = new ConfigurationSetting();
configurationSetting.SessionStore = new HybridWebThreadSessionStore("test"); //解决在Web环境中跨线程访问HttpContext的问题
configurationSetting.Properties.Add("nullableInt", "int?");
_engine = new DefaultConfigurationEngine(configurationSetting);
_engine.RegisterInterpreter(new XmlConfigurationInterpreter(resource));
IMapperFactory mapperFactory = _engine.BuildMapperFactory();
_sessionFactory = _engine.ModelStore.SessionFactory;
_dataMapper = ((IDataMapperAccessor)mapperFactory).DataMapper;
_sessionStore = ((IModelStoreAccessor)_dataMapper).ModelStore.SessionStore;
}
catch (Exception ex)
{
Exception e = ex;
while (e != null)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
e = e.InnerException;
}
throw;
}
if (_sessionFactory.DataSource.DbProvider.Id.IndexOf("PostgreSql") >= 0)
{
ConvertKey = new KeyConvert(Lower);
}
else if (_sessionFactory.DataSource.DbProvider.Id.IndexOf("oracle") >= 0)
{
ConvertKey = new KeyConvert(Upper);
}
else
{
ConvertKey = new KeyConvert(Normal);
}
}
public static DbHelper Instance
{
get
{
if (_instance == null)
{
lock (typeof(DbHelper))
{
if (_instance == null) //double-check
{
_instance = new DbHelper();
}
}
}
return _instance;
}
}
#endregion
/// <summary>
/// 数据映射器
/// </summary>
public IDataMapper DataMapper
{
get
{
return this._dataMapper;
}
}
/// <summary>
/// 会话工厂
/// </summary>
public ISessionFactory SessionFactory
{
get
{
return this._sessionFactory;
}
}
/// <summary>
/// 配置引擎
/// </summary>
public IConfigurationEngine Engine
{
get
{
return this._engine;
}
}
#region 辅助方法
private static string Normal(string key)
{
return key;
}
private static string Upper(string key)
{
return key.ToUpper();
}
private static string Lower(string key)
{
return key.ToLower();
}
#endregion
}
}
4、数据访问接口模版(IDAOTemplate.txt)
using System;
using System.Collections.Generic;
using System.Text;
namespace ${DAONameSpace}.Interface
{
using ${EntityNameSpace};
public interface I${EntityClassName}${DAOClassPostFix} : IBase${DAOClassPostFix}<${EntityClassName}>
{
}
}
5、数据访问类模版(DAOTemplate.txt)
using System;
using System.Collections.Generic;
using System.Text;
namespace ${DAONameSpace}.Implements
{
using ${EntityNameSpace};
using ${DAONameSpace}.Interface;
public class ${EntityClassName}${DAOClassPostFix} : Base${DAOClassPostFix}<${EntityClassName}>, I${EntityClassName}${DAOClassPostFix}
{
#region 构造方法
public ${EntityClassName}${DAOClassPostFix}() : base() { }
public ${EntityClassName}${DAOClassPostFix}(string language) : base(language) { }
#endregion
}
}
6、业务接口模版(IBIZTemplate.txt)
using System;
using System.Collections.Generic;
using System.Text;
namespace ${BIZNameSpace}.Interface
{
using ${EntityNameSpace};
public interface I${EntityClassName}${BIZClassPostFix} : IBase${BIZClassPostFix}<${EntityClassName}>
{
}
}
7、业务实现类模版(BIZTemplate.txt)
using System;
using System.Collections.Generic;
using System.Text;
namespace ${BIZNameSpace}.Implements
{
using ${EntityNameSpace};
using ${DAONameSpace}.Interface;
using ${DAONameSpace}.Implements;
using ${BIZNameSpace}.Interface;
public class ${EntityClassName}${BIZClassPostFix} : Base${BIZClassPostFix}<${EntityClassName}>, I${EntityClassName}${BIZClassPostFix}
{
#region 属性注入与构造方法
private I${EntityClassName}${DAOClassPostFix} ${CamelDAOClassPostFix};
public ${EntityClassName}${BIZClassPostFix}()
{
this.${CamelDAOClassPostFix} = new ${EntityClassName}${DAOClassPostFix}();
base.Base${DAOClassPostFix} = this.${CamelDAOClassPostFix};
}
public ${EntityClassName}${BIZClassPostFix}(string language)
{
this.${CamelDAOClassPostFix} = new ${EntityClassName}${DAOClassPostFix}(language);
base.Base${DAOClassPostFix} = this.${CamelDAOClassPostFix};
}
#endregion
}
}
8、数据访问基础接口模版(IBaseService.txt)
/************************************************************************************
* ${CopyRight}
* File:
* IBase${DAOClassPostFix}.cs
* Description:
* 数据访问基础接口
* Author:
* ${Author}
* ${AuthorEmail}
* ${Online}
* Finish DateTime:
* ${Date}
* History:
***********************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
namespace ${DAONameSpace}
{
using ${ComponentNameSpace};
public interface IBase${DAOClassPostFix}<T> where T : new()
{
/// <summary>
/// Type类型向DBType类型转换
/// </summary>
/// <param name="t">Type类型</param>
/// <returns>返回DBType</returns>
DbType TypeToDbType(Type t);
/// <summary>
/// 按照主键查找
/// </summary>
/// <param name="ids">主键参数列表</param>
/// <returns>返回主键对应的对象</returns>
T GetById(int objId);
/// <summary>
/// 按照主键查找
/// </summary>
/// <param name="ids">主键参数列表</param>
/// <returns>返回主键对象的对象</returns>
T GetById(Dictionary<string, object> ids);
/// <summary>
/// 指定条件的查询
/// </summary>
/// <param name="where">查询条件</param>
/// <returns>返回实体类的集合</returns>
IList<T> GetListByWhere(Dictionary<string,object> where);
/// <summary>
/// 指定条件的查询
/// </summary>
/// <param name="where">查询条件</param>
/// <returns>返回实体类的集合</returns>
IList<T> GetListByWhere(string where);
/// <summary>
/// 指定条件的查询
/// </summary>
/// <param name="entity">指定的实体属性作为条件</param>
/// <returns>返回实体类的集合</returns>
IList<T> GetListByEntity(T entity);
/// <summary>
/// 指定条件和排序的查询
/// </summary>
/// <param name="where">查询条件</param>
/// <param name="order">排序字段</param>
/// <returns>返回实体类的集合</returns>
IList<T> GetListByWhereAndOrder(Dictionary<string, object> where, string order);
/// <summary>
/// 指定条件和排序的查询
/// </summary>
/// <param name="where">查询条件</param>
/// <param name="order">排序字段</param>
/// <returns>返回实体类的集合</returns>
IList<T> GetListByWhereAndOrder(string where, string order);
/// <summary>
/// 指定条件的查询
/// </summary>
/// <param name="where">查询条件</param>
/// <returns>返回数据集</returns>
DataSet GetDataSetByWhere(Dictionary<string, object> where);
/// <summary>
/// 指定条件的查询
/// </summary>
/// <param name="where">查询条件</param>
/// <returns>返回数据集</returns>
DataSet GetDataSetByWhere(string where);
/// <summary>
/// 指定返回字段和阐述的查询
/// </summary>
/// <param name="returnFields">查询结果中应包含的字段,*代表所有字段</param>
/// <param name="parameters">查询条件</param>
/// <returns>返回符合查询条件指定字段列表的结果集</returns>
DataSet GetDataSetByFieldsAndParams(string returnFields, params KeyValuePair<string, object>[] parameters);
/// <summary>
/// 指定返回字段和参数的查询
/// </summary>
/// <param name="returnFields">查询结果中应包含的字段,*代表所有字段</param>
/// <param name="parameters">查询参数列表</param>
/// <returns>返回数据集</returns>
DataSet GetDataSetByFieldsAndParams(string returnFields, Dictionary<string, object> parameters);
/// <summary>
/// 查询所有记录并以List形式返回
/// </summary>
/// <returns></returns>
IList<T> GetAllList();
/// <summary>
/// 查找表中的记录并排序
/// </summary>
/// <param name="order">排序字段</param>
/// <returns>返回对应表的实体类的集合</returns>
IList<T> GetAllListOrder(string order);
/// <summary>
/// 返回指定排序的前N条记录
/// </summary>
/// <param name="n">返回结果中的记录数</param>
/// <param name="order">排序字段</param>
/// <returns>返回实体类的集合</returns>
IList<T> GetTopNListOrder(int n, string order);
/// <summary>
/// 返回指定条件和排序的前N条记录
/// </summary>
/// <param name="n">返回结果中的最大记录数</param>
/// <param name="where">筛选条件</param>
/// <param name="order">排序字段</param>
/// <returns>返回实体类的集合</returns>
IList<T> GetTopNListWhereOrder(int n, Dictionary<string, object> where, string order);
/// <summary>
/// 返回指定条件和排序的前N条记录
/// </summary>
/// <param name="n">返回结果中的最大记录数</param>
/// <param name="where">筛选条件</param>
/// <param name="order">排序字段</param>
/// <returns>返回实体类的集合</returns>
IList<T> GetTopNListWhereOrder(int n, string where, string order);
/// <summary>
/// 查询所有记录并以DataSet方式返回数据
/// </summary>
/// <returns></returns>
DataSet GetAllDataSet();
/// <summary>
/// 指定条件的查询
/// </summary>
/// <param name="stmtId">SQL语句Id</param>
/// <param name="values">查询条件</param>
/// <returns>返回数据集</returns>
DataSet GetDataSetByStmt(string stmtId, params KeyValuePair<string,object>[] values);
/// <summary>
/// 获取某个属性(数据列)的最大值
/// </summary>
/// <param name="propertyItem">属性(数据列)</param>
/// <returns>返回此属性(数据列)对应的最大值</returns>
object GetMaxValueByProperty(string propertyItem);
/// <summary>
/// 调用存储过程的分页查询方法
/// </summary>
/// <param name="pageResult">用于传递查询条件的分页类的对象</param>
/// <returns>返回封装了页面数据和总记录数据的分页类对象</returns>
PageResult<T> GetPageData(PageResult<T> pageResult);
/// <summary>
/// 调用基于SQL的存储过程的分页查询方法
/// </summary>
/// <param name="pageResult">用于传递查询条件的分页类的对象</param>
/// <returns>返回封装了页面数据和总记录数据的分页类对象,dataSet,recordCount</returns>
PageResult<T> GetPageDataBySql(PageResult<T> pageResult);
/// <summary>
/// 调用存储过程的分页查询方法
/// </summary>
/// <param name="stmtId">SQL语句对象Id</param>
/// <param name="pageResult">用于传递查询条件的分页类的对象</param>
/// <returns>返回封装了页面数据和总记录数据的分页类对象</returns>
PageResult<T> GetPageDataByReader(string stmtId, PageResult<T> pageResult);
/// <summary>
/// 调用存储过程的分页查询方法
/// </summary>
/// <param name="pageResult">用于传递查询条件的分页类的对象</param>
/// <returns>返回封装了页面数据和总记录数据的分页类对象</returns>
PageResult<T> GetPageDataByReader(PageResult<T> pageResult);
/// <summary>
/// 调用存储过程的分页查询方法
/// </summary>
/// <param name="stmtId">SQL语句对象Id</param>
/// <param name="pageResult">用于传递查询条件的分页类的对象</param>
/// <param name="values">参数</param>
/// <returns>返回封装了页面数据和总记录数据的分页类对象</returns>
PageResult<T> GetPageDataByReader(string stmtId, PageResult<T> pageResult, params KeyValuePair<string, object>[] values);
/// <summary>
/// 调用存储过程的分页查询方法
/// </summary>
/// <param name="stmtId">SQL语句对象Id</param>
/// <param name="pageResult">用于传递查询条件的分页类的对象</param>
/// <param name="parameters">参数</param>
/// <returns>返回封装了页面数据和总记录数据的分页类对象</returns>
PageResult<T> GetPageDataByReader(string stmtId, PageResult<T> pageResult, Dictionary<string, object>[] parameters);
/// <summary>
/// 分页查询方法,基于分页存储过程
/// </summary>
/// <param name="pageResult">用于传递查询条件的分页类的对象</param>
/// <returns>返回封装了页面数据和总页数、总记录数的结果集的数据集</returns>
DataSet GetPageDataSet(PageResult<T> pageResult);
/// <summary>
/// 执行存储过程的方法
/// </summary>
/// <param name="stmtId">存储过程的语句对象Id</param>
/// <param name="values">存储过程的参数值</param>
/// <returns>返回存储过程执行后对应的数据集</returns>
DataSet GetDataSetByStoreProcedure(string stmtId, params KeyValuePair<string, object>[] values);
/// <summary>
/// 执行存储过程的方法
/// </summary>
/// <param name="stmtId">存储过程的语句对象Id</param>
/// <param name="values">存储过程的参数</param>
/// <returns>返回存储过程执行后对应的数据集</returns>
DataSet GetDataSetByStoreProcedure(string stmtId, Dictionary<string, object> values);
/// <summary>
/// 获取符合条件的记录数
/// </summary>
/// <param name="stmtId">SQL语句对象ID</param>
/// <param name="values">参数</param>
/// <returns>返回符合条件的记录数</returns>
int GetRowCount(string stmtId, params KeyValuePair<string, object>[] values);
/// <summary>
/// 获取符合条件的记录数
/// </summary>
/// <param name="values">参数</param>
/// <returns>返回符合条件的记录数</returns>
int GetRowCount(params KeyValuePair<string, object>[] values);
/// <summary>
/// 获取符合条件的记录数
/// </summary>
/// <param name="where">条件</param>
/// <returns>返回符合条件的记录数</returns>
int GetRowCountByWhere(string where);
/// <summary>
/// 添加新记录
/// </summary>
/// <param name="entity">对应新记录的实体数据</param>
/// <returns>返回追加记录的主键值</returns>
int Insert(T entity);
/// <summary>
/// 批量添加新纪录
/// </summary>
/// <param name="lst">对应的List记录</param>
/// <returns>返回受影响的记录行数</returns>
int BatchInsert(List<T> lst);
/// <summary>
/// 更新记录
/// </summary>
/// <param name="entity">需要更新记录对应的实体数据</param>
/// <returns>返回更新的记录数</returns>
int Update(T entity);
/// <summary>
/// 按条件更新
/// </summary>
/// <param name="stmtId">更新语句对象Id</param>
/// <param name="values">参数</param>
/// <returns>返回更新的记录数</returns>
int UpdateByStmt(string stmtId, params KeyValuePair<string, object>[] values);
/// <summary>
/// 按条件更新
/// </summary>
/// <param name="stmtId">更新语句对象Id</param>
/// <param name="values">参数</param>
/// <returns>返回更新的记录数</returns>
int UpdateByStmt(string stmtId, Dictionary<string, object> values);
/// <summary>
/// 按条件更新
/// </summary>
/// <param name="fieldSetValue">字段及更新的值,可以多个</param>
/// <param name="where">条件表达式</param>
/// <returns>返回更新的记录数</returns>
int UpdateFields(string fieldSetValue, string where);
/// <summary>
/// 删除主键是id值得记录
/// </summary>
/// <param name="id">要删除记录的主键值</param>
/// <returns>返回删除的记录条数</returns>
int Delete(object id);
/// <summary>
/// 删除对象对应的记录
/// </summary>
/// <param name="entity">与要删除记录对应的对象</param>
int Delete(T entity);
/// <summary>
/// 按指定的条件删除数据
/// </summary>
/// <param name="stmtId">删除语句对象Id</param>
/// <param name="values">参数</param>
/// <returns>返回删除的记录数</returns>
int DeleteByStmt(string stmtId, params KeyValuePair<string, object>[] values);
/// <summary>
/// 按指定的条件删除数据
/// </summary>
/// <param name="stmtId">删除语句对象Id</param>
/// <param name="values">参数</param>
/// <returns>返回删除的记录数</returns>
int DeleteByStmt(string stmtId, Dictionary<string, object> values);
/// <summary>
/// 删除指定条件的记录
/// </summary>
/// <param name="where">条件</param>
/// <returns>返回删除的记录数</returns>
int DeleteByWhere(string where);
/// <summary>
/// 清除表中所有记录
/// </summary>
void ClearData();
}
}
9、数据访问基础类模版(BaseService.txt)
/************************************************************************************
* ${CopyRight}
* File:
* Base${DAOClassPostFix}.cs
* Description:
* 基于泛型数据访问抽象基类
* Author:
* ${Author}
* ${AuthorEmail}
* ${Online}
* Finish DateTime:
* ${Date}
* History:
*
***********************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Data;
using System.Data.SqlClient;
namespace ${DAONameSpace}
{
using ${ComponentNameSpace};
using MyBatis.DataMapper.MappedStatements;
using MyBatis.DataMapper.Scope;
using MyBatis.DataMapper.Session;
using MyBatis.DataMapper;
/// <summary>
/// 基于泛型数据访问抽象基类,封装了基本数据访问操作CRUD
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class Base${DAOClassPostFix}<T> : IBase${DAOClassPostFix}<T> where T : new()
{
#region 私有字段
private readonly string procedureName = "MesnacPaging"; //分页存储过程名 -for sql2000/2005/2008
private readonly string pagerProductName = "PagerShow"; //基于SQL语句分页的存储过程名--for sql2005/2008
protected string tableName = String.Empty; //对应泛型的表名
protected string stmtPrefix = String.Empty; //MyBatis语句标识前缀
#endregion
#region 构造方法
public Base${DAOClassPostFix}()
{
this.stmtPrefix = typeof(T).Name;
this.tableName = this.stmtPrefix;
}
public Base${DAOClassPostFix}(string language)
{
this.stmtPrefix = language + typeof(T).Name;
this.tableName = this.stmtPrefix;
}
#endregion
#region IBase${DAOClassPostFix}<T> 成员
/// <summary>
/// Type类型向DBType类型转换
/// </summary>
/// <param name="t">Type类型</param>
/// <returns>返回DBType</returns>
public DbType TypeToDbType(Type t)
{
DbType dbt;
try
{
dbt = (DbType)Enum.Parse(typeof(DbType), t.Name);
}
catch
{
dbt = DbType.Object;
}
return dbt;
}
/// <summary>
/// 按照主键查找
/// </summary>
/// <param name="ids">主键参数列表</param>
/// <returns></returns>
public T GetById(int objId)
{
string stmtId = "GetById";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("ObjId", objId);
T entity = DbHelper.Instance.DataMapper.QueryForObject<T>(stmtId, parameters);
return entity;
}
public T GetById(Dictionary<string, object> ids)
{
string stmtId = "GetById";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
T entity = DbHelper.Instance.DataMapper.QueryForObject<T>(stmtId, ids);
return entity;
}
/// <summary>
/// 指定条件的查询
/// </summary>
/// <param name="where">查询条件</param>
/// <returns>返回实体类的集合</returns>
public IList<T> GetListByWhere(Dictionary<string, object> where)
{
string stmtId = "GetListByWhere";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
IList<T> resultList = DbHelper.Instance.DataMapper.QueryForList<T>(stmtId, where);
return resultList;
}
/// <summary>
/// 指定条件的查询
/// </summary>
/// <param name="where">查询条件</param>
/// <returns>返回实体类的集合</returns>
public IList<T> GetListByWhere(string where)
{
string stmtId = "GetListByWhereStr";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("where", where);
IList<T> resultList = DbHelper.Instance.DataMapper.QueryForList<T>(stmtId, parameters);
return resultList;
}
/// <summary>
/// 指定条件的查询
/// </summary>
/// <param name="entity">指定的实体属性作为条件</param>
/// <returns>返回实体类的集合</returns>
public IList<T> GetListByEntity(T entity)
{
string stmtId = "GetListByWhere";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
IList<T> resultList = DbHelper.Instance.DataMapper.QueryForList<T>(stmtId, entity);
return resultList;
}
/// <summary>
/// 指定条件和排序的查询
/// </summary>
/// <param name="where">查询条件</param>
/// <param name="order">排序字段</param>
/// <returns>返回实体类的集合</returns>
public IList<T> GetListByWhereAndOrder(Dictionary<string, object> where, string order)
{
string stmtId = "GetListByWhereAndOrder";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
where.Add("OrderBy", order);
IList<T> resultList = DbHelper.Instance.DataMapper.QueryForList<T>(stmtId, where);
return resultList;
}
/// <summary>
/// 指定条件和排序的查询
/// </summary>
/// <param name="where">查询条件</param>
/// <param name="order">排序字段</param>
/// <returns>返回实体类的集合</returns>
public IList<T> GetListByWhereAndOrder(string where, string order)
{
string stmtId = "GetListByWhereAndOrderStr";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("where", where);
if (!String.IsNullOrEmpty(order))
{
parameters.Add("OrderBy", order);
}
IList<T> resultList = DbHelper.Instance.DataMapper.QueryForList<T>(stmtId, parameters);
return resultList;
}
/// <summary>
/// 指定条件的查询
/// </summary>
/// <param name="where">查询条件</param>
/// <returns>返回数据集</returns>
public DataSet GetDataSetByWhere(Dictionary<string, object> where)
{
string stmtId = "GetDataSetByWhere";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
DataTable tableResult = DbHelper.Instance.DataMapper.QueryForDataTable(stmtId, where);
DataSet dsResult = new DataSet();
dsResult.Tables.Add(tableResult);
return dsResult;
}
/// <summary>
/// 指定条件的查询
/// </summary>
/// <param name="where">查询条件</param>
/// <returns>返回数据集</returns>
public DataSet GetDataSetByWhere(string where)
{
string stmtId = "GetDataSetByWhereStr";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("where", where);
DataTable tableResult = DbHelper.Instance.DataMapper.QueryForDataTable(stmtId, parameters);
DataSet dsResult = new DataSet();
dsResult.Tables.Add(tableResult);
return dsResult;
}
/// <summary>
/// 指定返回字段和阐述的查询
/// </summary>
/// <param name="returnFields">查询结果中应包含的字段,*代表所有字段</param>
/// <param name="parameters"></param>
/// <returns></returns>
public DataSet GetDataSetByFieldsAndParams(string returnFields, params KeyValuePair<string, object>[] parameters)
{
returnFields = String.IsNullOrEmpty(returnFields) ? "*" : returnFields;
Dictionary<string, object> newParameters = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> kv in parameters)
{
newParameters.Add(kv.Key, kv.Value);
}
return this.GetDataSetByFieldsAndParams(returnFields, newParameters);
}
/// <summary>
/// 指定返回字段和参数的查询
/// </summary>
/// <param name="parameters">查询结果中应包含的字段,*代表所有字段</param>
/// <param name="values">查询参数列表</param>
/// <returns>返回数据集</returns>
public DataSet GetDataSetByFieldsAndParams(string returnFields, Dictionary<string, object> parameters)
{
string stmtId = "GetDataSetByFieldsAndParams";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
returnFields = String.IsNullOrEmpty(returnFields) ? "*" : returnFields;
parameters.Add("ColumnNames", returnFields);
DataTable tableResult = DbHelper.Instance.DataMapper.QueryForDataTable(stmtId, parameters);
DataSet dsResult = new DataSet();
dsResult.Tables.Add(tableResult);
return dsResult;
}
/// <summary>
/// 查询所有记录并以List形式返回
/// </summary>
/// <returns></returns>
public IList<T> GetAllList()
{
string stmtId = "GetAllListOrder"; //与GetAllListOrder共用同一语句
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
IList<T> resultList = DbHelper.Instance.DataMapper.QueryForList<T>(stmtId, null);
return resultList;
}
/// <summary>
/// 查找表中的记录并排序
/// </summary>
/// <param name="order">排序字段</param>
/// <returns>返回对应表的实体类的集合</returns>
public IList<T> GetAllListOrder(string order)
{
string stmtId = "GetAllListOrder";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
Dictionary<string, object> parameters = new Dictionary<string, object>();
if (!String.IsNullOrEmpty(order))
{
parameters.Add("OrderBy", order);
}
IList<T> resultList = DbHelper.Instance.DataMapper.QueryForList<T>(stmtId, parameters);
return resultList;
}
/// <summary>
/// 返回指定排序的前N条记录
/// </summary>
/// <param name="n">返回结果中的记录数</param>
/// <param name="order">排序字段</param>
/// <returns>返回实体类的集合</returns>
public IList<T> GetTopNListOrder(int n, string order)
{
string stmtId = "GetTopNListWhereOrder"; //与GetTopNListWhereOrder共用同一语句
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("Top", n);
if (!String.IsNullOrEmpty(order))
{
parameters.Add("OrderBy", order);
}
IList<T> resultList = DbHelper.Instance.DataMapper.QueryForList<T>(stmtId, parameters);
return resultList;
}
/// <summary>
/// 返回指定条件和排序的前N条记录
/// </summary>
/// <param name="n">返回结果中的最大记录数</param>
/// <param name="where">筛选条件</param>
/// <param name="order">排序字段</param>
/// <returns>返回实体类的集合</returns>
public IList<T> GetTopNListWhereOrder(int n, Dictionary<string, object> where, string order)
{
string stmtId = "GetTopNListWhereOrder";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
where.Add("Top", n);
if (!String.IsNullOrEmpty(order))
{
where.Add("OrderBy", order);
}
IList<T> resultList = DbHelper.Instance.DataMapper.QueryForList<T>(stmtId, where);
return resultList;
}
/// <summary>
/// 返回指定条件和排序的前N条记录
/// </summary>
/// <param name="n">返回结果中的最大记录数</param>
/// <param name="where">筛选条件</param>
/// <param name="order">排序字段</param>
/// <returns>返回实体类的集合</returns>
public IList<T> GetTopNListWhereOrder(int n, string where, string order)
{
string stmtId = "GetTopNListWhereOrderStr";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("Top", n);
parameters.Add("where", where);
if (!String.IsNullOrEmpty(order))
{
parameters.Add("OrderBy", order);
}
IList<T> resultList = DbHelper.Instance.DataMapper.QueryForList<T>(stmtId, parameters);
return resultList;
}
/// <summary>
/// 查询所有记录并以DataSet方式返回数据
/// </summary>
/// <returns>以DataSet方式返回表中所有数据</returns>
public DataSet GetAllDataSet()
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
return this.GetDataSetByWhere(parameters);
}
/// <summary>
/// 指定条件的查询
/// </summary>
/// <param name="stmtId">SQL语句Id</param>
/// <param name="values">查询条件</param>
/// <returns>返回数据集</returns>
public DataSet GetDataSetByStmt(string stmtId, params KeyValuePair<string,object>[] values)
{
if (stmtId.IndexOf(".") == -1)
{
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
}
System.Collections.Hashtable parameters = new System.Collections.Hashtable();
if (values != null)
{
foreach (var kv in values)
{
parameters.Add(kv.Key, kv.Value);
}
}
DataSet dsResult = DbHelper.Instance.DataMapper.QueryForDataSet(stmtId, parameters);
return dsResult;
}
/// <summary>
/// 获取某个属性(数据列)的最大值
/// </summary>
/// <param name="propertyItem">属性(数据列)</param>
/// <returns>返回此属性(数据列)对应的最大值</returns>
public object GetMaxValueByProperty(string propertyItem)
{
string stmtId = "GetMaxValueByProperty";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("ColumnName", propertyItem);
object result = DbHelper.Instance.DataMapper.QueryForObject(stmtId, parameters);
return (result as System.Collections.Hashtable)[""];
}
/// <summary>
/// 调用存储过程的分页查询方法
/// </summary>
/// <param name="pageResult">用于传递查询条件的分页类的对象</param>
/// <returns>返回封装了页面数据和总记录数据的分页类对象</returns>
public PageResult<T> GetPageData(PageResult<T> pageResult)
{
pageResult.Data.Clear();
string stmtId = "GetPageDataMesnacPagging";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
System.Collections.Hashtable parameters = new System.Collections.Hashtable();
if (this.tableName.StartsWith("["))
{
parameters.Add("TableName", this.tableName);
}
else
{
parameters.Add("TableName", String.Format("[{0}]", this.tableName));
}
parameters.Add("ReturnFields", pageResult.ReturnFields);
parameters.Add("PageSize", pageResult.PageSize);
parameters.Add("PageIndex", pageResult.PageIndex);
parameters.Add("Where", pageResult.Where);
parameters.Add("Orderfld", pageResult.Orderfld);
parameters.Add("OrderType", pageResult.OrderType);
IList resultList = DbHelper.Instance.DataMapper.QueryForList(stmtId, parameters);
pageResult.Data = resultList[0] as List<T>;
pageResult.RecordCount = Convert.ToInt32((resultList[1] as List<Hashtable>)[0]["RecordCount"]);
return pageResult;
}
/// <summary>
/// 调用基于SQL的存储过程的分页查询方法
/// </summary>
/// <param name="pageResult">用于传递查询条件的分页类的对象</param>
/// <returns>返回封装了页面数据和总记录数据的分页类对象,dataSet,recordCount</returns>
public PageResult<T> GetPageDataBySql(PageResult<T> pageResult)
{
pageResult.Data.Clear();
string stmtId = "GetPageDataPagerShow";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
System.Collections.Hashtable parameters = new System.Collections.Hashtable();
parameters.Add("QueryStr", pageResult.QueryStr);
parameters.Add("PageSize", pageResult.PageSize);
parameters.Add("PageCurrent", pageResult.PageIndex);
parameters.Add("FdShow", pageResult.ReturnFields);
parameters.Add("FdOrder", pageResult.Orderfld);
parameters.Add("Rows", 0);
IList<T> resultList = DbHelper.Instance.DataMapper.QueryForList<T>(stmtId, parameters);
pageResult.Data = resultList as List<T>;
pageResult.RecordCount = Convert.ToInt32(parameters["Rows"]);
return pageResult;
}
/// <summary>
/// 调用存储过程的分页查询方法
/// </summary>
/// <param name="stmtId">SQL语句对象Id</param>
/// <param name="pageResult">用于传递查询条件的分页类的对象</param>
/// <returns>返回封装了页面数据和总记录数据的分页类对象</returns>
public PageResult<T> GetPageDataByReader(string stmtId, PageResult<T> pageResult)
{
if (stmtId.IndexOf(".") == -1)
{
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
}
System.Collections.Hashtable parameters = new System.Collections.Hashtable();
parameters.Add("ReturnFields", pageResult.ReturnFields);
parameters.Add("PageSize", pageResult.PageSize);
parameters.Add("PageIndex", pageResult.PageIndex);
parameters.Add("Where", pageResult.Where);
parameters.Add("Orderfld", pageResult.Orderfld);
parameters.Add("OrderType", pageResult.OrderType);
using (IDataReader reader = DbHelper.Instance.DataMapper.QueryForDataReader(stmtId, parameters))
{
int begin = pageResult.PageSize * (pageResult.PageIndex - 1) + 1;
int count = 0;
int pageSize = 0;
DataTable table = new DataTable();
for (int i = 0; i < reader.FieldCount; i++)
{
DataColumn col = new DataColumn(reader.GetName(i), reader.GetFieldType(i));
table.Columns.Add(col);
}
while (reader.Read())
{
count++;
if (count >= begin && pageSize < pageResult.PageSize)
{
DataRow row = table.NewRow();
for (int i = 0; i < reader.FieldCount; i++)
{
row[i] = reader[i];
}
table.Rows.Add(row);
pageSize++;
}
}
reader.Close();
DataSet ds = new DataSet();
ds.Tables.Add(table);
pageResult.DataSet = ds;
pageResult.RecordCount = count;
}
return pageResult;
}
/// <summary>
/// 调用存储过程的分页查询方法
/// </summary>
/// <param name="pageResult">用于传递查询条件的分页类的对象</param>
/// <returns>返回封装了页面数据和总记录数据的分页类对象</returns>
public PageResult<T> GetPageDataByReader(PageResult<T> pageResult)
{
string stmtId = "GetPageDataByReader";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
return this.GetPageDataByReader(stmtId, pageResult);
}
/// <summary>
/// 调用存储过程的分页查询方法
/// </summary>
/// <param name="stmtId">SQL语句对象Id</param>
/// <param name="pageResult">用于传递查询条件的分页类的对象</param>
/// <param name="values">参数</param>
/// <returns>返回封装了页面数据和总记录数据的分页类对象</returns>
public PageResult<T> GetPageDataByReader(string stmtId, PageResult<T> pageResult, params KeyValuePair<string, object>[] values)
{
if (stmtId.IndexOf(".") == -1)
{
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
}
System.Collections.Hashtable parameters = new System.Collections.Hashtable();
if (values != null)
{
foreach (var kv in values)
{
parameters.Add(kv.Key, kv.Value);
}
}
using (IDataReader reader = DbHelper.Instance.DataMapper.QueryForDataReader(stmtId, parameters))
{
int begin = pageResult.PageSize * (pageResult.PageIndex - 1) + 1;
int count = 0;
int pageSize = 0;
DataTable table = new DataTable();
for (int i = 0; i < reader.FieldCount; i++)
{
DataColumn col = new DataColumn(reader.GetName(i), reader.GetFieldType(i));
table.Columns.Add(col);
}
while (reader.Read())
{
count++;
if (count >= begin && pageSize < pageResult.PageSize)
{
DataRow row = table.NewRow();
for (int i = 0; i < reader.FieldCount; i++)
{
row[i] = reader[i];
}
table.Rows.Add(row);
pageSize++;
}
}
reader.Close();
DataSet ds = new DataSet();
ds.Tables.Add(table);
pageResult.DataSet = ds;
pageResult.RecordCount = count;
}
return pageResult;
}
/// <summary>
/// 调用存储过程的分页查询方法
/// </summary>
/// <param name="stmtId">SQL语句对象Id</param>
/// <param name="pageResult">用于传递查询条件的分页类的对象</param>
/// <param name="parameters">参数</param>
/// <returns>返回封装了页面数据和总记录数据的分页类对象</returns>
public PageResult<T> GetPageDataByReader(string stmtId, PageResult<T> pageResult, Dictionary<string, object>[] parameters)
{
if (stmtId.IndexOf(".") == -1)
{
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
}
using (IDataReader reader = DbHelper.Instance.DataMapper.QueryForDataReader(stmtId, parameters))
{
int begin = pageResult.PageSize * (pageResult.PageIndex - 1) + 1;
int count = 0;
int pageSize = 0;
DataTable table = new DataTable();
for (int i = 0; i < reader.FieldCount; i++)
{
DataColumn col = new DataColumn(reader.GetName(i), reader.GetFieldType(i));
table.Columns.Add(col);
}
while (reader.Read())
{
count++;
if (count >= begin && pageSize < pageResult.PageSize)
{
DataRow row = table.NewRow();
for (int i = 0; i < reader.FieldCount; i++)
{
row[i] = reader[i];
}
table.Rows.Add(row);
pageSize++;
}
}
reader.Close();
DataSet ds = new DataSet();
ds.Tables.Add(table);
pageResult.DataSet = ds;
pageResult.RecordCount = count;
}
return pageResult;
}
/// <summary>
/// 分页查询方法,基于分页存储过程
/// </summary>
/// <param name="pageResult">用于传递查询条件的分页类的对象</param>
/// <returns>返回封装了页面数据和总页数、总记录数的结果集的数据集</returns>
public DataSet GetPageDataSet(PageResult<T> pageResult)
{
pageResult.Data.Clear();
string stmtId = "GetPageDataSet";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
System.Collections.Hashtable parameters = new System.Collections.Hashtable();
if (this.tableName.StartsWith("["))
{
parameters.Add("TableName", this.tableName);
}
else
{
parameters.Add("TableName", String.Format("[{0}]", this.tableName));
}
parameters.Add("ReturnFields", pageResult.ReturnFields);
parameters.Add("PageSize", pageResult.PageSize);
parameters.Add("PageIndex", pageResult.PageIndex);
parameters.Add("Where", pageResult.Where);
parameters.Add("Orderfld", pageResult.Orderfld);
parameters.Add("OrderType", pageResult.OrderType);
DataSet ds = DbHelper.Instance.DataMapper.QueryForDataSet(stmtId, parameters);
return ds;
}
/// <summary>
/// 执行存储过程的方法
/// </summary>
/// <param name="stmtId">存储过程的语句对象Id</param>
/// <param name="values">存储过程的参数值</param>
/// <returns>返回存储过程执行后对应的数据集</returns>
public DataSet GetDataSetByStoreProcedure(string stmtId, params KeyValuePair<string, object>[] values)
{
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
Hashtable parameters = new Hashtable();
foreach (KeyValuePair<string, object> kv in values)
{
parameters.Add(kv.Key, kv.Value);
}
DataSet ds = DbHelper.Instance.DataMapper.QueryForDataSet(stmtId, parameters);
return ds;
}
/// <summary>
/// 执行存储过程的方法
/// </summary>
/// <param name="stmtId">存储过程的语句对象Id</param>
/// <param name="values">存储过程的参数</param>
/// <returns>返回存储过程执行后对应的数据集</returns>
public DataSet GetDataSetByStoreProcedure(string stmtId, Dictionary<string, object> values)
{
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
DataSet ds = DbHelper.Instance.DataMapper.QueryForDataSet(stmtId, values);
return ds;
}
/// <summary>
/// 获取符合条件的记录数
/// </summary>
/// <param name="stmtId">SQL语句对象ID</param>
/// <param name="values">参数</param>
/// <returns>返回符合条件的记录数</returns>
public int GetRowCount(string stmtId , params KeyValuePair<string,object>[] values)
{
if (stmtId.IndexOf(".") == -1)
{
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
}
Hashtable parameters = new Hashtable();
foreach (KeyValuePair<string, object> kv in values)
{
parameters.Add(kv.Key, kv.Value);
}
int result = DbHelper.Instance.DataMapper.QueryForObject<int>(stmtId, parameters);
return result;
}
/// <summary>
/// 获取符合条件的记录数
/// </summary>
/// <param name="values">参数</param>
/// <returns>返回符合条件的记录数</returns>
public int GetRowCount(params KeyValuePair<string, object>[] values)
{
string stmtId = "GetRowCount";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
return this.GetRowCount(stmtId, values);
}
/// <summary>
/// 获取符合条件的记录数
/// </summary>
/// <param name="where">条件</param>
/// <returns>返回符合条件的记录数</returns>
public int GetRowCountByWhere(string where)
{
string stmtId = "GetRowCountByWhere";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
int result = DbHelper.Instance.DataMapper.QueryForObject<int>(stmtId, where);
return result;
}
/// <summary>
/// 添加新记录
/// </summary>
/// <param name="entity">对应新记录的实体数据</param>
/// <returns>返回追加记录的主键值</returns>
public int Insert(T entity)
{
string stmtId = "Insert";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
object result = DbHelper.Instance.DataMapper.Insert(stmtId, entity);
return Convert.ToInt32(result);
}
/// <summary>
/// 批量添加新纪录
/// </summary>
/// <param name="lst">对应的List记录</param>
/// <returns>返回受影响的记录行数</returns>
public int BatchInsert(List<T> lst)
{
string stmtId = "Insert";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
foreach (T entity in lst)
{
object result = DbHelper.Instance.DataMapper.Insert(stmtId, entity);
}
return Convert.ToInt32(lst.Count);
}
/// <summary>
/// 更新记录
/// </summary>
/// <param name="entity">需要更新记录对应的实体数据</param>
/// <returns>返回更新的记录数</returns>
public int Update(T entity)
{
string stmtId = "Update";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
object result = DbHelper.Instance.DataMapper.Update(stmtId, entity);
return Convert.ToInt32(result);
}
/// <summary>
/// 按条件更新
/// </summary>
/// <param name="stmtId">更新语句对象Id</param>
/// <param name="values">参数</param>
/// <returns>返回更新的记录数</returns>
public int UpdateByStmt(string stmtId, params KeyValuePair<string, object>[] values)
{
if (stmtId.IndexOf(".") == -1)
{
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
}
Hashtable parameters = new Hashtable();
foreach (KeyValuePair<string, object> kv in values)
{
parameters.Add(kv.Key, kv.Value);
}
int result = DbHelper.Instance.DataMapper.Update(stmtId, parameters);
return result;
}
/// <summary>
/// 按条件更新
/// </summary>
/// <param name="stmtId">更新语句对象Id</param>
/// <param name="values">参数</param>
/// <returns>返回更新的记录数</returns>
public int UpdateByStmt(string stmtId, Dictionary<string, object> values)
{
if (stmtId.IndexOf(".") == -1)
{
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
}
int result = DbHelper.Instance.DataMapper.Update(stmtId, values);
return result;
}
/// <summary>
/// 按条件更新
/// </summary>
/// <param name="fieldSetValue">字段及更新的值,可以多个</param>
/// <param name="where">条件表达式</param>
/// <returns>返回更新的记录数</returns>
public int UpdateFields(string fieldSetValue, string where)
{
string stmtId = "UpdateFields";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("FieldSetValue", fieldSetValue);
parameters.Add("where", where);
int result = DbHelper.Instance.DataMapper.Update(stmtId, parameters);
return result;
}
/// <summary>
/// 删除主键是id值得记录
/// </summary>
/// <param name="id">要删除记录的主键值</param>
/// <returns>返回删除的记录条数</returns>
public int Delete(object id)
{
string stmtId = "Delete";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
int result = DbHelper.Instance.DataMapper.Delete(stmtId, id);
return result;
}
/// <summary>
/// 删除对象对应的记录
/// </summary>
/// <param name="entity">与要删除记录对应的对象</param>
public int Delete(T entity)
{
string stmtId = "DeleteByEntity";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
int result = DbHelper.Instance.DataMapper.Delete(stmtId, entity);
return result;
}
/// <summary>
/// 按指定的条件删除数据
/// </summary>
/// <param name="stmtId">删除语句对象Id</param>
/// <param name="values">参数</param>
/// <returns>返回删除的记录数</returns>
public int DeleteByStmt(string stmtId, params KeyValuePair<string, object>[] values)
{
if (stmtId.IndexOf(".") == -1)
{
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
}
Hashtable parameters = new Hashtable();
foreach (KeyValuePair<string, object> kv in values)
{
parameters.Add(kv.Key, kv.Value);
}
int result = DbHelper.Instance.DataMapper.Delete(stmtId, parameters);
return result;
}
/// <summary>
/// 按指定的条件删除数据
/// </summary>
/// <param name="stmtId">删除语句对象Id</param>
/// <param name="values">参数</param>
/// <returns>返回删除的记录数</returns>
public int DeleteByStmt(string stmtId, Dictionary<string, object> values)
{
if (stmtId.IndexOf(".") == -1)
{
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
}
int result = DbHelper.Instance.DataMapper.Delete(stmtId, values);
return result;
}
/// <summary>
/// 删除指定条件的记录
/// </summary>
/// <param name="where">条件</param>
/// <returns>返回删除的记录数</returns>
public int DeleteByWhere(string where)
{
string stmtId = "DeleteByWhere";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
int result = DbHelper.Instance.DataMapper.Delete(stmtId, where);
return result;
}
/// <summary>
/// 清除表中所有记录
/// </summary>
public void ClearData()
{
string stmtId = "ClearData";
stmtId = String.Format("{0}.{1}", this.stmtPrefix, stmtId);
DbHelper.Instance.DataMapper.QueryForObject(stmtId, null);
}
#endregion
#region 辅助方法
/// <summary>
/// 得到运行时ibatis.net动态生成的SQL
/// </summary>
/// <param name="sqlMapper"></param>
/// <param name="statementName"></param>
/// <param name="paramObject"></param>
/// <returns></returns>
protected virtual string GetRuntimeSql(string statementName, object paramObject)
{
string result = string.Empty;
try
{
IMappedStatement statement = DbHelper.Instance.Engine.ModelStore.GetMappedStatement(statementName);
if (null == DbHelper.Instance.Engine.ModelStore.SessionStore.CurrentSession)
{
DbHelper.Instance.Engine.ModelStore.SessionFactory.OpenSession();
}
Console.WriteLine(DbHelper.Instance.Engine.ModelStore.SessionStore.CurrentSession.Connection.State);
RequestScope scope = statement.Statement.Sql.GetRequestScope(statement, paramObject, DbHelper.Instance.Engine.ModelStore.SessionStore.CurrentSession);
result = scope.PreparedStatement.PreparedSql;
Console.WriteLine(result);
foreach (IDbDataParameter para in scope.PreparedStatement.DbParameters)
{
Console.WriteLine("{0} = {1}", para.ParameterName, para.Value);
}
}
catch (Exception ex)
{
result = "获取SQL语句出现异常:" + ex.Message;
Console.Write(result);
}
return result;
}
#endregion
}
}
完整代码下载
上一篇: 交管12123怎么分享给朋友? 交管12123分享到微信qq的技巧
下一篇: 数据库表结构