当前位置:网站首页>Net small and medium-sized enterprise project development framework series (one)
Net small and medium-sized enterprise project development framework series (one)
2022-07-05 21:43:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm the king of the whole stack , I've prepared for you today Idea Registration code .
The front end at that time , We've developed based on Net A set of structures sprint.NET+NHibernate+MVC+WCF+EasyUI Wait for small and medium-sized Enterprises Level system development platform , Now I'll sort out the progress of the whole development process and share it with you , This series may be a little long . Guide and learn more .
Our underlying development platform is sprint.NET+NHibernate+MVC+WCF+EasyUI Way to develop , Add some by the way Spring.net The injection part , Of course, our most basic work is about permission design 、 Business design , And architecture . We haven't learned too complicated architecture . We still use it most often MVC The architecture begins to expand
Reference material :
<< restructure , Improve the design of existing code >>
<<.net Application architecture design principles , Patterns and practices >>
<<.net Design paradigm >>
<< Clean code >>
First of all, we want to explain the construction of the project , Our project is mainly divided into 6 part , Business logic layer . Data access layer , Page layer , The data model layer and part of a common class , On this basis, we abstract the corresponding interfaces in each layer , In this way, the upper layer only needs to be on the next layer , Interface oriented programming . At the same time Spring.NET To the relationship between management . Achieve decoupling .
This is mainly :
Business logic layer :
ICMSBLL: Business logic layer interface
CMSBLL: Business logic layer implementation
Abstract data underlying encapsulation ( Generic )
ICommonSupportDAL: Abstraction of public methods
CommonSupportDAL: Implementation of public methods
Data access layer :
ICMSDAL: Data access layer interface
CMSDAL: Data access layer implementation
Domain model layer :
Entity: This is a EF Build a model
Set class layer :
Collections: Encapsulates paging , For the addition, deletion, modification and query inside the collection class , Add, delete, modify and check the internal classes of the collection class .
Interface layer :
ComplaintManageSystem: Basic MVC and LigerUI The interface part of the implementation
TZHSWEET.UI: About MVC public UI Part of the definition
Public class library part :
Our goal is “0” The data access layer implementation of adding, deleting, modifying and querying , Mainly by Nhibernate The definition of general addition, deletion and modification from , Then other classes inherit the interface of adding, deleting, modifying and querying and the corresponding interface of their own defined subclasses , Realize expansion
First , We know from our experience in writing code , our Dao It is mainly about adding, deleting, modifying and checking , Let's first define an interface of a public method called ICommonSupportDAL, This interface defines generic addition, deletion, modification and query
<span style="font-family:FangSong_GB2312;font-size:18px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entity;
namespace ICommonSupportDAL
{
public interface IRepository<T, TCollection> where T : class
{
#region Instant query , adopt ID Inquire about
/// <summary>
/// Get entities
/// </summary>
/// <param name="id"> Primary key </param>
/// <returns> Entity </returns>
T Get(object id);
#endregion
#region Defered Loading , adopt ID Inquire about
/// <summary>
/// Get entities
/// </summary>
/// <param name="id"> Primary key </param>
/// <returns> Entity </returns>
T Load(T entity);
#endregion
#region Persist data to database
/// <summary>
/// Insert entity
/// </summary>
/// <param name="entity"> Entity </param>
/// <returns>ID</returns>
object Save(T entity);
#endregion
#region Update data information
/// <summary>
/// Change entities
/// </summary>
/// <param name="entity"> Entity </param>
void Update(T entity);
#endregion
#region If the data exists, change the information , If not, insert
/// <summary>
/// If the data exists, change the information , If not, insert
/// </summary>
/// <param name="entity"> Entity </param>
void SaveOrUpdate(T entity);
#endregion
#region Delete entities
/// <summary>
/// Delete entities
/// </summary>
/// <param name="id">ID</param>
void Delete(T entity);
#endregion
#region basis ID Delete entities in batch
// Delete entities
//void Delete(T entity);
/// <summary>
/// basis ID Delete entities in batch
/// </summary>
/// <param name="idList">ID aggregate </param>
void Delete(IList<T> idList);
#endregion
/// <summary>
/// Get all collections
/// </summary>
/// <returns> aggregate </returns>
//IQueryable<T> LoadAll();
/// <summary>
/// Paging to get all sets
/// </summary>
/// <param name="count"> Record the total number </param>
/// <param name="pageIndex"> Page number </param>
/// <param name="pageSize"> The size of each page </param>
/// <returns> aggregate </returns>
//IQueryable<T> LoadAllWithPage(out long count, int pageIndex, int pageSize);
#region Unconditionally query all entities ( Single table query )
/// <summary>
/// Unconditionally query all entities ( Single table query )
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
TCollection LoadAll();
#endregion
#region Write by yourself where Conditional query entity
/// <summary>
/// Write by yourself where Conditional query entity
/// </summary>
/// <param name="whereSql"></param>
/// <returns></returns>
TCollection LoadAllByWhereSql(object whereSql);
#endregion
#region Delete according to a certain condition field
/// <summary>
/// Delete on condition
/// </summary>
/// <param name="columName"> Field name </param>
/// <param name="columValue"> field value </param>
void DeleteAfterQuery(object columName, object columValue);
#endregion
#region Query by one condition ( Single table query )
/// <summary>
/// Query by one condition
/// </summary>
/// <param name="columnName"></param>
/// <param name="columValue"></param>
/// <returns></returns>
TCollection getByCondition(object columnName, object columValue);
#endregion
#region Through the native sql Statement to add, delete, modify and query
/// <summary>
/// Through the native sql Statement to add, delete, modify and query
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
TCollection ExecuteOrQueryBySql(object sql);
#endregion
#region Multiconditional query
/// <summary>
/// Multiconditional query
/// </summary>
/// <returns></returns>
TCollection FindVer(QueryHelper<T> qh);
#endregion
#region basis SQL Statement query
/// <summary>
/// basis SQL Statement query
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
TCollection LoadAllBySql(string sql);
#endregion
#region Query according to a certain field ( Multi-table query )
/// <summary>
/// Query according to a certain field ( Multi-table query )
/// </summary>
/// <param name="columnName"></param>
/// <param name="columValue"></param>
/// <returns></returns>
TCollection LoadByCondition(object columnName, object columValue);
#endregion
}
}
</span>
This layer interface , You may feel no need , But , This interface is very important , This interface ensures that we use Nhibernate When an abstract class implements addition, deletion, modification and query, it also adds the self extensibility of subclasses .
Next , Namely Dao part , We need to design very carefully ,
First of all, we need to design a Nhibernate Implementation of the public parent class CommonSupportDAL class , Use it to add, delete, modify and check ,
<span style="font-family:FangSong_GB2312;font-size:18px;"><span style="color:#000000;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Data.NHibernate.Generic.Support;
using NHibernate;
using System.Linq.Expressions;
using System.Collections;
using ICommonSupportDAL;
using Entity;
using MCS.Library.Data.DataObjects;
using System.Reflection;
using Collections;
namespace CommonSupportDAL
{
/// <summary>
/// Data access layer public interface implementation
/// </summary>
/// <typeparam name="T"> Entity generics </typeparam>
public class RepositoryBase<T, TCollection> : HibernateDaoSupport, IRepository<T, TCollection>
where T : class
where TCollection : Collection<T, TCollection> ,new()
{
public String TEntityName;
public RepositoryBase()
{
String name = typeof(T).ToString();
this.TEntityName = name.Substring(name.LastIndexOf('.') + 1);
}
#region Persist entities to the database
/// <summary>
/// Persist entities to the database
/// </summary>
/// <param name="entity"> Generic entity </param>
/// <returns></returns>
public virtual object Save(T entity)
{
// this.HibernateTemplate.Find<T>("from UserInfo ");
try
{
this.HibernateTemplate.SessionFactory.GetCurrentSession().FlushMode = FlushMode.Auto;
}catch(Exception ex)
{
}
Object TEntity = this.HibernateTemplate.Save(entity);
this.HibernateTemplate.Flush();
return TEntity;
}
#endregion
#region basis ID Inquire about
/// <summary>
/// basis ID Inquire about
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public virtual T Get(object id)
{
return this.HibernateTemplate.Get<T>(id);
}
#endregion
#region basis ID Inquire about
/// <summary>
/// basis ID Inquire about
/// </summary>
/// <param name="id"> Entity ID</param>
/// <returns></returns>
public virtual T Load(T entity)
{
Object fild=null;
try
{
fild = entity.GetType().GetProperty("ID").GetValue(entity, null);
}
catch (Exception ex)
{
string typename = entity.GetType().ToString();
throw new Exception(" Please check " + typename + " Whether there is a primary key in ID!");
}
return this.HibernateTemplate.Load<T>(fild);
}
#endregion
#region Query all entity information
/// <summary>
/// Query all entity information
/// </summary>
/// <returns></returns>
public virtual TCollection LoadAll()
{
TCollection tcollecton = new TCollection();
IList<T> list = this.HibernateTemplate.LoadAll<T>();
tcollecton.CopyFrom(list);
return tcollecton;
}
#endregion
#region Query entity set information according to conditions (hql)
/// <summary>
/// Query entity set information according to conditions (hql)
/// </summary>
/// <returns></returns>
public virtual TCollection LoadAllByWhereSql(object whereSql)
{
TCollection tcollecton = new TCollection();
IList<T> list = this.HibernateTemplate.Find<T>("from " + TEntityName + " where " + whereSql);
tcollecton.CopyFrom(list);
return tcollecton;
}
#endregion
#region Query entity set information according to conditions (sql)
/// <summary>
/// Query entity set information according to conditions (sql)
/// </summary>
/// <returns></returns>
public virtual TCollection LoadAllBySql(string sql)
{
TCollection tcollecton = new TCollection();
IList<T> list = this.HibernateTemplate.Find<T>(sql);
tcollecton.CopyFrom(list);
return tcollecton;
}
#endregion
#region Update entity information
/// <summary>
/// Update entity information
/// </summary>
/// <param name="entity"></param>
public virtual void Update(T entity)
{
this.HibernateTemplate.SessionFactory.GetCurrentSession().FlushMode = FlushMode.Auto;
this.HibernateTemplate.Update(entity);
this.HibernateTemplate.Flush();
}
#endregion
#region basis ID Delete the information
/// <summary>
/// basis ID Delete the information
/// </summary>
/// <param name="id"></param>
public void Delete(T entity)
{
this.HibernateTemplate.SessionFactory.GetCurrentSession().FlushMode = FlushMode.Auto;
this.HibernateTemplate.Delete(entity);
this.HibernateTemplate.Flush();
}
#endregion
#region Batch deletion
/// <summary>
/// Batch deletion
/// </summary>
/// <param name="idList"></param>
public virtual void Delete(IList<T> idList)
{
foreach (object item in idList)
{
this.HibernateTemplate.SessionFactory.GetCurrentSession().FlushMode = FlushMode.Auto;
this.HibernateTemplate.Delete(item);
this.HibernateTemplate.Flush();
}
}
#endregion
#region Delete on condition
/// <summary>
/// Delete on condition
/// </summary>
/// <param name="columName"></param>
/// <param name="columValue"></param>
public virtual void DeleteAfterQuery(object columName, object columValue)
{
IList<T> list = this.HibernateTemplate.Find<T>("from " + TEntityName + " u where u." + columName + " =?", new object[] { columValue });
// Delete at run time
foreach (object t in list)
{
this.HibernateTemplate.SessionFactory.GetCurrentSession().FlushMode = FlushMode.Auto;
this.HibernateTemplate.Delete(t);
this.HibernateTemplate.Flush();
}
}
#endregion
#region Update after saving
/// <summary>
/// Update after saving
/// </summary>
/// <param name="entity"></param>
public virtual void SaveOrUpdate(T entity)
{
this.HibernateTemplate.SessionFactory.GetCurrentSession().FlushMode = FlushMode.Auto;
this.HibernateTemplate.SaveOrUpdate(entity);
this.HibernateTemplate.Flush();
}
#endregion
//#region
///// <summary>
///// Query entity set information according to conditions --sql sentence , It is not recommended to use , Will produce sql Inject
///// </summary>
///// <returns></returns>
//public virtual IList<T> getBywhereSql(string wheresql)
//{
// IList<T> list = this.HibernateTemplate.Find<T>("from " + TName + " where " + wheresql);
// return list;
//}
//#endregion
//#region
//#endregion
///// <summary>
///// Query entity set information according to conditions --sql sentence , It is not recommended to use . Will produce sql Inject
///// </summary>
///// <returns></returns>
//public virtual IList<T> getBySql(string sql)
//{
// IList<T> list = this.HibernateTemplate.Find<T>(sql);
// return list;
//}
#region Query through a condition ( Single table query )
/// <summary>
/// Query through a condition ( Single table query )
/// </summary>
/// <param name="columName"> Property name </param>
/// <param name="columValue"> Property value </param>
/// <returns></returns>
public virtual TCollection getByCondition(object columnName, object columValue)
{
TCollection tcoll = new TCollection();
// For example, verification username. Just need to pass in Name The name and value of the attribute can be ;
// This Name Is the attribute name of the corresponding entity , Non database field name . example getByCondition("Name","11");
/*
* Tips : This line of code is too long , The system automatically comments without highlighting . One click Copy removes system comments
* IList<T> list = this.HibernateTemplate.Find<T>("from " + TEntityName + " u where u." + columnName + " =?", new object[] { columValue }); tcoll.CopyFrom(list); return tcoll; } #endregion #region Query through a condition ( Multi-table query ) /// <summary> /// Query through a condition ( Single table query ) /// </summary> /// <param name="columName"> Property name </param> /// <param name="columValue"> Property value </param> /// <returns></returns> public virtual TCollection LoadByCondition(object columnName, object columValue) { TCollection tcoll = new TCollection(); // For example, verification username, Just need to pass in Name The name and value of the attribute can be ; // This Name Is the attribute name of the corresponding entity . Non database field name . example getByCondition("Name","11"); IList<T> list = this.HibernateTemplate.Find<T>("from " + TEntityName + " u where u." + columnName + " =?", new object[] { columValue }); tcoll=this.LoadById(list); return tcoll; } #endregion #region Through the native sql Statement to add, delete, modify and query /// <summary> /// Through the native sql Statement to add, delete, modify and query /// </summary> /// <param name="sql"></param> /// <returns></returns> public TCollection ExecuteOrQueryBySql(object sql) { TCollection tcollecton = new TCollection(); ISQLQuery sqlQuery = this.HibernateTemplate.SessionFactory.GetCurrentSession().CreateSQLQuery(sql.ToString()).AddEntity(typeof(T)); tcollecton.CopyFrom(sqlQuery.List<T>()); return tcollecton; } #endregion #region Multiconditional query /// <summary> /// Multiconditional query /// </summary> /// <returns></returns> public TCollection FindVer(QueryHelper<T> qh) { // QueryHelper<T> qh = new QueryHelper<T>("u"); //return qh; // Parameter list IList<Object> parameters = qh.getParameters(); // Query the data list on this page IQuery listQuery = this.HibernateTemplate.SessionFactory.GetCurrentSession().CreateQuery(qh.getListQueryHql()); // Create query object if (parameters != null) { // Set parameters for (int i = 0; i < parameters.Count; i++) { listQuery.SetParameter(i, parameters[i]); } } listQuery.List(); TCollection tcollection = new TCollection(); IList<T> list = listQuery.List<T>(); tcollection.CopyFrom(list); return tcollection; } #endregion #region Paging query /// <summary> /// Paging query /// </summary> /// <param name="tcollection"></param> /// <returns></returns> public TCollection LoadAllByPage(TCollection tcollection) { IQuery query = this.HibernateTemplate.SessionFactory.OpenSession().CreateQuery("from "+typeof(T).ToString()); query.SetFirstResult((tcollection.PageNum - 1) * tcollection.PageSize); query.SetMaxResults(tcollection.PageSize); IList list = query.List(); TCollection tcoll = new TCollection(); tcoll.TotalRecords=this.LoadAll().Count(); IEnumerator en = list.GetEnumerator(); while (en.MoveNext()) { tcoll.Add((T)en.Current); } //tcoll.CopyFrom(list); return tcoll; } #endregion #region Through multiple ID Inquire about /// <summary> /// Through multiple ID Inquire about /// </summary> /// <param name="entity"> Include ID Entity set of information </param> /// <returns> Aggregate information </returns> public TCollection LoadById(IList<T> entity) { IEnumerator en = entity.GetEnumerator(); IList<object> IDlist = new List<object>(); while (en.MoveNext()) { Object fild = null; try { fild = en.Current.GetType().GetProperty("ID").GetValue(en.Current, null); } catch (Exception ex) { string typename = en.Current.GetType().ToString(); throw new Exception(" Please check " + typename + " Whether there is a primary key in ID!"); } IDlist.Add("'"+fild+"'"); } IQuery query = this.HibernateTemplate.SessionFactory.OpenSession().CreateQuery("from " + TEntityName + " u where u.ID in (" +string.Join(",",IDlist.ToArray())+")"); // IQuery query = this.HibernateTemplate.SessionFactory.OpenSession().CreateQuery("from " + TEntityName + " u where u.ID in ('05221ff5-b491-4590-86bb-f5e275c6fd83','10df07ac-98ae-41f8-bcde-c4f48ec931f4','14c33f83-3be7-4162-8ace-8ef2e3677402','29780cc4-d7d8-4982-b8b7-ee63320da1d8','299ad880-06e3-48a3-80ca-570b8a557c42','7662b072-42a7-45fc-b11b-93efc844e5cd','87c26a14-56f2-4a57-9c99-e55f55ba6cdd','87c73291-591b-431f-b0fe-e73e15a490cf','917f9354-29e2-44b0-ad58-e2d8a0dd7670','9de57d2d-b4f8-4c56-9ce6-66673f42413d','a0e0cb9a-e8e4-4164-a021-cbcb61a8ea30','c6c239bf-6089-4c7c-983c-8ca479c360d5','c996d768-c9f9-4575-9268-4cfcf92fd038','ca09c55e-0a8d-4241-a364-74f1bdb60c32','da34ebae-11a7-4cfc-9772-b5e049768fe7','e5ee288e-8c5d-46bc-8c77-34b8c45750c1')"); IList list= query.List(); TCollection tc= new TCollection(); IEnumerator enumer=list.GetEnumerator(); while(enumer.MoveNext()) { tc.Add((T)enumer.Current); } return tc; } #endregion }}</span></span>
*/
Next, our workload will be small , We can see the results , Our next implementation , Just inherit the above RepositoryBase and IRepository Can be easily implemented , The addition, deletion, modification and query of subclasses and the extension of subclasses .
<span style="font-family:FangSong_GB2312;font-size:18px;"><span style="color:#000000;"> public interface ICaseAssignEntityRepository:IRepository<CaseAssignEntity,CaseAssignEntityCollection>
{
}</span></span>
<span style="font-family:FangSong_GB2312;font-size:18px;">namespace CMSDAL.AnJianLuRu
{
public class CaseAssignEntityRepository : RepositoryBase<CaseAssignEntity, CaseAssignEntityCollection>, ICaseAssignEntityRepository
{
}
}</span>
You can see that there are two inheritances, one is RepositoryBase Parent class . One is ICaseAssignEntityRepository Own business logic interface ( It realizes the expansion of subclasses , For example, you want to add methods specific to a class . Just fill in your own interface ). Through this inheritance system, we can ensure that we put an interface outside at the same time to ensure scalability .
Inherit series diagram :
summary
So our data access layer , Very easy to achieve , Basically, the amount of code is very small , Adding, deleting, modifying and checking parts are almost ”0″ Code , Are implemented by the generic parent class . abstract 、 Inherit 、 Generic 、 Entrustment 、 Containers and so on greatly improve the reusability of code .
—– Everything comes from abstraction .
That's all for today , Next, I'll explain to you Collection Encapsulation and abstraction of . expect !
Copyright notice : This article is an original blog article , Blog , Without consent , Shall not be reproduced .
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/117581.html Link to the original text :https://javaforall.cn
边栏推荐
- MMAP
- EasyExcel的讀寫操作
- Summarize the reasons for 2XX, 3xx, 4xx, 5xx status codes
- Access Zadig self-test environment outside the cluster based on ingress controller (best practice)
- Learning notes of statistical learning methods -- Chapter 1 Introduction to statistical learning methods
- @Validated basic parameter verification, grouping parameter verification and nested parameter verification
- Gcc9.5 offline installation
- An exception occurred in Huawei game multimedia calling the room switching method internal system error Reason:90000017
- MATLAB | App Designer·我用MATLAB制作了一款LATEX公式实时编辑器
- postgis 安装地理信息扩展
猜你喜欢
JMeter installation under win7
matlab绘制hsv色轮图
Cold violence -- another perspective of objective function setting
MMAP learning
Realize the function of verifying whether the user has completed login when browsing the page
Zhang Lijun: penetrating uncertainty depends on four "invariants"
SQL knowledge leak detection
Experienced inductance manufacturers tell you what makes the inductance noisy. Inductance noise is a common inductance fault. If the used inductance makes noise, you don't have to worry. You just need
MMAP学习
Display DIN 4102-1 Class B1 fire test requirements
随机推荐
Get JS of the previous day (timestamp conversion)
华为游戏多媒体调用切换房间方法出现异常Internal system error. Reason:90000017
怎么利用Tensorflow2进行猫狗分类识别
Robot framework setting variables
Deployment of Jenkins under win7
An exception occurred in Huawei game multimedia calling the room switching method internal system error Reason:90000017
crm创建基于fetch自己的自定义报告
使用Aspect制作全局异常处理类
Zhang Lijun: la pénétration de l’incertitude dépend de quatre « invariants»
Alibaba cloud award winning experience: build a highly available system with polardb-x
【日常训练】729. 我的日程安排表 I
Environment configuration problem record
Feng Tang's "spring breeze is not as good as you" digital collection, logged into xirang on July 8!
int GetMonth( ) const throw( );后面的throw( )什么意思?
办公遇到的问题--
Postgres establish connection and delete records
Kingbasees v8r3 data security case - audit record clearing case
Yolov5 training custom data set (pycharm ultra detailed version)
ESP32
深信服X计划-网络协议基础 DNS