我这里主要分成了两个xml来进行spring.net管理实际情况中可自己根据需要进行分类 Dao2.xml <?xml version="1.0" encoding="utf-8" ?> <objects xmlns="http://www.springframework.net" xmlns:db="http://www.springframework.net/database" xmlns:tx="http://www.springframework.net/tx"> <description>Data Access Objects.</description> <object id="ClassicDao" type="Framework.Impl.Dao.ClassicDao, Framework.Impl"> <property name="HibernateTemplate" ref="CHibernateTemplate"/> <property name="AdoTemplate" ref="CAdoTemplate"/> </object> <object id="AccessBatcher" type="Framework.Impl.Service.OracleAccessBatcher, Framework.Impl"> <property name="HibernateTemplate" ref="CHibernateTemplate"/> <property name="AdoTemplate" ref="CAdoTemplate"/> </object> <!-- placeholder configurer--> <object type="Spring.Objects.Factory.Config.PropertyPlaceholderConfigurer, Spring.Core"> <property name="ConfigSections" value="databaseSettings"/> </object> <!-- Database and NHibernate Configuration --> <!--<db:provider id="DbProvider" provider="OracleClient-2.0" connectionString="Data Source=(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = ${db.datasource})(PORT = ${db.port})) (ADDRESS = (PROTOCOL = TCP)(HOST = ${db.datasource2})(PORT = ${db.port})) (load_balance=yes) )(CONNECT_DATA = (SERVICE_NAME = ${db.database})(server = dedicated)) ); User Id=${db.user};Password=${db.password};"/>--> <db:provider id="DbProvider" provider="OracleODP-11-3.0" connectionString="Data Source=(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = ${db.datasource})(PORT =${db.port})) (ADDRESS = (PROTOCOL = TCP)(HOST = ${db.datasource2})(PORT =${db.port})) (load_balance=yes) )(CONNECT_DATA = (SERVICE_NAME = ${db.database})(server = dedicated)) ); User Id=${db.user};Password=${db.password};"/> <object id="SessionFactory" type="Spring.Data.NHibernate.LocalSessionFactoryObject"> <property name="DbProvider" ref="DbProvider"/> <property name="MappingAssemblies"> <list> <value>HRAModel</value> <value>BASModel</value> <value>RSKModel</value> <value>MKTModel</value> <value>TRANModel</value> <value>ImportModel</value> <value>ETLModel</value> <value>CCRModel</value> <value>ALMModel</value> <value>HraUtility</value> <value>POSModel</value> </list> </property> <property name="HibernateProperties"> <dictionary> <entry key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/> <entry key="dialect" value="NHibernate.Dialect.Oracle10gDialect"/> <!--<entry key="connection.driver_class" value="NHibernate.Driver.OracleClientDriver"/>--> <entry key="connection.driver_class" value="NHibernate.Driver.OracleDataClientDriver"/> <!--<entry key="use_outer_join" value="true"/>--> <entry key="show_sql" value="true"/> <entry key="use_proxy_validator" value="true"/> <!--<entry key="hbm2ddl.auto" value="update"/>--> <!--<entry key="hibernate.current_session_context_class" value="Spring.Data.NHibernate.SpringSessionContext, Spring.Data.NHibernate30"/>--> <entry key="hibernate.current_session_context_class" value="thread"/> </dictionary> </property> <!-- 必须增加此项说明,与 Spring 的声明式事务集成 --> <property name="ExposeTransactionAwareSessionFactory" value="true" /> </object> <!--事务切面 kexb修改与2016.5.14--> <tx:attribute-driven transaction-manager="TxManager" /> <!-- Classic Template --> <object id="CHibernateTemplate" type="Spring.Data.NHibernate.HibernateTemplate"> <property name="SessionFactory" ref="SessionFactory" /> <property name="TemplateFlushMode" value="Auto" /> <property name="CacheQueries" value="true" /> </object> <object id="CAdoTemplate" type="Spring.Data.Core.AdoTemplate, Spring.Data"> <property name="DbProvider" ref="DbProvider"/> <property name="DataReaderWrapperType" value="Spring.Data.Support.NullMappingDataReader, Spring.Data"/> </object> </objects> Service.xml <?xml version="1.0" encoding="utf-8" ?> <objects xmlns="http://www.springframework.net"> <object id="CommonService" type="Framework.Impl.Service.CommonService, Framework.Impl"> <property name="Dao" ref="ClassicDao"/> <property name="Cache" ref="AspNetCache"/> <property name="Scheduler" ref="QuartzScheduler"/> </object> <object id="AspNetCache" type="Spring.Caching.AspNetCache, Spring.Web"> <property name="SlidingExpiration" value="true"/> <property name="TimeToLive" value="00:22:00"/> </object> <object id="QuartzWeeklyCalendar" type="Framework.Impl.Quartz.WorkHourCalendar, Framework.Impl"> <property name="WorkingHoursUtcExp" value="0:00-4:00,5:00-10:00"/> <property name="IncludedDatesOfMonthService" value="@(WorkDateService).FindWorkDays(#iYear,#iMonth)"/> </object> <object id="QuartzScheduler" type="Spring.Scheduling.Quartz.SchedulerFactoryObject, Spring.Scheduling.Quartz"> <property name="Calendars"> <dictionary> <entry key="default" value-ref="QuartzWeeklyCalendar" /> </dictionary> </property> <property name="QuartzProperties"> <dictionary> <entry key="quartz.threadPool.threadCount" value="2" /> </dictionary> </property> </object> <!--Wcf ServiceModel Extensions 仅处理此列表登记的类型--> <object id="WcfInterceptor" lazy-init="true" type="System.Collections.ArrayList,mscorlib"> <constructor-arg> <list> <object type="Framework.Integration.WCF.NHibernate.HibernateDataContractSurrogate, Framework.Integration"/> <object type="Framework.Integration.WCF.FaultErrorHandler, Framework.Integration"/> <ref object="WcfMsgLog"/> </list> </constructor-arg> </object> <object id="WcfOsiv" lazy-init="true" type="Spring.Data.NHibernate.Support.SessionScope"/> <object id="WcfMsgLog" lazy-init="true" type="Framework.Integration.WCF.DispatchMessageInspector, Framework.Integration"> <constructor-arg name="enableLog" value="false"/> <constructor-arg name="osiv" ref="WcfOsiv"/> </object> <!--事务自动AOP控制--> <object name="autoProxyCreator" type="Spring.Aop.Framework.AutoProxy.ObjectNameAutoProxyCreator, Spring.Aop"> <property name="InterceptorNames" value="transactionInterceptor"/> <property name="ObjectNames"> <list> <value>*Service</value> <value>*BLL</value> <!--拦截目标对象--> </list> </property> </object> <object id="transactionInterceptor" type="Spring.Transaction.Interceptor.TransactionInterceptor"> <property name="TransactionManager" ref="TxManager"/> <property name="TransactionAttributes"> <name-values> <add key="Save*" value="PROPAGATION_REQUIRED"/> <!--拦截方法名--> <add key="Find*" value="PROPAGATION_SUPPORTS,readOnly"/> <add key="LimitControl" value="PROPAGATION_REQUIRED"/> </name-values> </property> </object> <object id="TxManager" type="Spring.Data.NHibernate.HibernateTransactionManager"> <property name="DbProvider" ref="DbProvider"/> <property name="SessionFactory" ref="SessionFactory"/> </object> </objects> Dao层封装 这里我是hibernatetemplate模板做的,因为spring.net事务管理里面已经对session进行了管理,而我比较任性想要既可以配置管理,也可以手动管理(方法中请注意 GetSession的[Transaction(ReadOnly=true)])特性注解 classicdao.cs using System; using System.Data; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; #if NHIBERNATE //NHibernate Template using NHibernate; #endif #if ADO_NET //Ado Template using Spring.Data.Core; using Spring.Data.Common; #endif //Query Info using Framework.IDao; using Framework.Domain; using Framework; using Spring.Data; using Spring.Data.NHibernate.Generic; using System.Diagnostics; using System.Reflection; using Oracle.DataAccess.Client; using System.Runtime.Remoting.Messaging; using NHibernate.Type; using NHibernate.Context; using Spring.Transaction.Interceptor; using Spring.Stereotype; namespace Framework.Impl.Dao { public class ClassicDao : IClassicDao { #if NHIBERNATE private Spring.Data.NHibernate.HibernateTemplate hibernateTemplate; public Spring.Data.NHibernate.HibernateTemplate HibernateTemplate { get { return hibernateTemplate; } set { hibernateTemplate = value; } } public object FindById(Type type, object id) { return HibernateTemplate.Load(type, id); } public IList FindAll(Type type) { return HibernateTemplate.LoadAll(type); } public object FindOne(QueryInfo info) { return HibernateTemplate.Execute(delegate (ISession session) { IQuery q = null; if (info.NamedQuery == null) { info.QueryObject = info.ToHQLString(); foreach (System.Collections.Generic.KeyValuePair<string, string> filter in info.Filters)//Enable Filter session.EnableFilter(filter.Value).SetParameter(filter.Key, info.Parameters[filter.Key]); q = session.CreateQuery(info.QueryObject + info.ToOrderBy()); } else q = session.GetNamedQuery(info.NamedQuery); SetParameters(q, info, HibernateTemplate); return q.UniqueResult(); }); } int CurrentCapacity = -1; public IList FindList(QueryInfo info) { return (IList)HibernateTemplate.Execute(delegate (ISession session) { IQuery q = null; if (info.NamedQuery == null) { info.QueryObject = info.ToHQLString(); foreach (System.Collections.Generic.KeyValuePair<string, string> filter in info.Filters)//Enable Filter session.EnableFilter(filter.Value).SetParameter(filter.Key, info.Parameters[filter.Key]); q = session.CreateQuery(info.QueryObject + info.ToOrderBy()); } else q = session.GetNamedQuery(info.NamedQuery); SetParameters(q, info, HibernateTemplate); #region Check License Capacity //if (CurrentCapacity == -1)//每次初始化运行 //{ // if (LicenseValidator.Capacity > 0) // { // int i = GetUserCount(); // if (i > LicenseValidator.Capacity + 1) // throw new UnauthorizedAccessException(string.Format("当前用户数'{0}'已超过授权最大用户数'{1}',系统已转为试用模式. 请确认License文件有效,且正确放在bin目录.", i, LicenseValidator.Capacity)); // else // CurrentCapacity = i;//成功初始化 // } // else // CurrentCapacity = 0;//成功初始化 //} #endregion if (info.NamedQuery == null && info.TotalCount > 0)//进行分页过滤? { if (info.TotalCount == 1)//取总条数,分页 info.TotalCount = GetTotalCount(info); q.SetFirstResult(info.StartRecord); q.SetMaxResults(info.PageSize); } return q.List(); }); } public int GetTotalCount(QueryInfo info)//统计总条数 { long i = (long)HibernateTemplate.Execute(delegate (ISession session) { if (info.QueryObject == null) throw new ArgumentNullException("QueryObject", "info.QueryObject can't not be null in GetTotalCount."); if (info.QueryObject.IndexOf("from") < 0)//Get Count directly? info.QueryObject = info.ToHQLString(); string sCountHQL = string.Format("SELECT COUNT({0}) {1}", info.CountField , info.QueryObject.Substring(info.QueryObject.IndexOf("from")));//from ... if (info.Parameters.ContainsKey("NO_COUNT"))//分页时移除此条件、此参数 { sCountHQL = sCountHQL.Replace(info.Where["NO_COUNT"], string.Empty); info.Parameters.Remove("NO_COUNT"); } foreach (System.Collections.Generic.KeyValuePair<string, string> filter in info.Filters)//Enable Filter session.EnableFilter(filter.Value).SetParameter(filter.Key, info.Parameters[filter.Key]); IQuery q = session.CreateQuery(sCountHQL); SetParameters(q, info, HibernateTemplate); q.SetResultTransformer(null);//Important return q.UniqueResult(); }); return Convert.ToInt32(i); } public static void SetParameters(IQuery q, QueryInfo info, Spring.Data.NHibernate.HibernateAccessor accessor) { // LicenseValidator.Validate(); if (info.Transformer != null) { Type transType; transType = info.Transformer as Type; if (transType == null && info.Transformer is string) transType = Type.GetType((string)info.Transformer); if (transType == null) throw new ArgumentException("Resultset 'Transformer' type could not be found."); q.SetResultTransformer(NHibernate.Transform.Transformers.AliasToBean(transType)); } if (info.NamedQuery != null) { System.Text.StringBuilder sb = null; bool bQueryReplaced = false; IDictionary namedParams = null; string sNullExp = " is null";//prop=:prop => prop is null int iWhere = q.QueryString.IndexOf("where", StringComparison.InvariantCultureIgnoreCase); foreach (System.Collections.Generic.KeyValuePair<string, object> p in info.Parameters)//if (!info.Filters.ContainsKey(p.Key))//bypass filter params { #region 更新Where后语句支持参数NULL值:NamedSQL请不要使同一参数在where前后同时出现! //select Col = :FormType from A where FormType=:FormType => select Col = from A Where FormType is null. //其中where之前的参数为NHibernate替换.NamedSQL请不要使同一参数在where前后同时出现! if (iWhere > 0 && p.Value == null) { bool bReplaced = false;//重置 if (sb == null) sb = new System.Text.StringBuilder(q.QueryString); Regex regex = new Regex(string.Format(@"([=><]+)(s*):{0}", p.Key)); MatchCollection mc = regex.Matches(sb.ToString()); for (int i = mc.Count - 1; i > -1; i--) { Match mt = mc[i]; if (mt.Index > iWhere)//仅更新Where后语句 { sb.Replace(mt.Value, sNullExp, mt.Index, mt.Length); bQueryReplaced = true; bReplaced = true; } } if (bReplaced)//where 后更新成功 { if (namedParams == null) namedParams = NHibernateHack.GetNamedParameterMap(q); NHibernateHack.AddTypedValue(namedParams, p.Key); continue;//参数不再需要了 } } #endregion accessor.ApplyNamedParameterToQuery(q, p.Key, p.Value, ((p.Value == null || p.Value is string) ? NHibernate.NHibernateUtil.AnsiString : null)); } if (bQueryReplaced)//更新QueryString NHibernateHack.SetQueryString(q, sb.ToString()); } else foreach (System.Collections.Generic.KeyValuePair<string, object> p in info.Parameters) if (!info.Filters.ContainsKey(p.Key))//bypass filter params accessor.ApplyNamedParameterToQuery(q, p.Key, p.Value, ((p.Value == null || p.Value is string) ? NHibernate.NHibernateUtil.AnsiString : null)); } #region Misc public object SaveOrUpdate(object obj) { Entity o = obj as Entity; if (o == null) throw new ArgumentException("Obj should be inherit from class [Entity]!"); if (o.State.New) Save(obj); else if (o.State.Deleted) Delete(obj); else if (o.State.Dirty) Update(obj); if (o.State.Deleted)//删除时不返回 return null; else return obj; } public void Flush() { HibernateTemplate.Flush(); } public void Evict(object obj) { HibernateTemplate.Evict(obj); } private int GetUserCount() { int i = 0; if (this.AdoTemplate != null) { QueryInfo info = new QueryInfo(); info.CustomSQL = "select count(1) from SYS_USER"; i = Convert.ToInt32(this.ExecuteScalar(info)); } return i; } public void Save(object obj) { HibernateTemplate.Execute(delegate (ISession session) { session.Save(obj); if (session.Transaction.IsActive) { session.Flush(); } return null; }); } public void Update(object obj) { HibernateTemplate.Execute(delegate (ISession session) { session.Merge(obj); if (session.Transaction.IsActive) { session.Flush(); } return null; }); } public void Delete(object obj) { HibernateTemplate.Execute(delegate (ISession session) { session.Delete(obj); if (session.Transaction.IsActive) { session.Flush(); } return null; }); } /// <summary> /// 请不要使同一参数在where前后同时出现! /// </summary> public int ExecuteUpdate(QueryInfo info) { int i = (int)HibernateTemplate.Execute(delegate (ISession session) { IQuery q = null; if (info.NamedQuery == null) { info.QueryObject = info.ToHQLString(); foreach (System.Collections.Generic.KeyValuePair<string, string> filter in info.Filters)//Enable Filter session.EnableFilter(filter.Value).SetParameter(filter.Key, info.Parameters[filter.Key]); q = session.CreateQuery(info.QueryObject + info.ToOrderBy()); } else q = session.GetNamedQuery(info.NamedQuery); SetParameters(q, info, HibernateTemplate); int ii = q.ExecuteUpdate(); if (session.Transaction.IsActive) { session.Flush(); } return ii; }); return i; } #endregion #endif #if ADO_NET public object ExecuteScalar(QueryInfo info) { IDbParameters ps = AdoAccessorHelper.PrepareCommand(AdoTemplate, info); object o = AdoTemplate.ExecuteScalar(info.NamedQuery == null ? CommandType.Text : CommandType.StoredProcedure , info.QueryObject, ps); if (info.TotalCount == 1) AdoAccessorHelper.FetchOutputParameters(ps, info); return o; } public IList<T> ExecuteRowMapper<T>(QueryInfo info, IRowMapper mapper) where T : new() { ISession session = GetSession(); { IDbParameters ps = AdoAccessorHelper.PrepareCommand(AdoTemplate, info); bool bOutput = false; int i; if (info.TotalCount == 1)//进行分页? { bOutput = true; if (info.NamedQuery == null) { i = info.QueryObject.IndexOf("from", StringComparison.InvariantCultureIgnoreCase); string sCountSQL = string.Format("SELECT COUNT({0}) {1}", info.CountField , info.QueryObject.Substring(i));//from ... info.TotalCount = Convert.ToInt32(AdoTemplate.ExecuteScalar(CommandType.Text, sCountSQL, ps)); AdoAccessorHelper.BuildPagingSQL(AdoTemplate, info); } } IDbCommand command = session.Connection.CreateCommand(); for (int j = 0; j < ps.Count; j++) { var p = command.CreateParameter(); p.ParameterName = ps[j].ParameterName; p.Value = ps[j].Value; command.Parameters.Add(p); } command.CommandText = info.QueryObject + info.ToOrderBy(); IDataReader reader = command.ExecuteReader(); IList<T> li = new List<T>(); Type mapperType = mapper.GetType(); MethodInfo[] mis = mapperType.GetMethods(); while (reader.Read()) { foreach (MethodInfo mi in mis) { if (mi.Name == "MapRow") { li.Add((T)mi.Invoke(mapper, new object[] { reader, 0 })); } } } reader.Close(); //IList li = AdoTemplate.QueryWithRowMapper(info.NamedQuery == null ? CommandType.Text : CommandType.StoredProcedure // , info.QueryObject + info.ToOrderBy(), mapper, ps); if (bOutput) AdoAccessorHelper.FetchOutputParameters(ps, info); return li; } } public IList ExecuteRowMapper(QueryInfo info, IRowMapper mapper) { IDbParameters ps = AdoAccessorHelper.PrepareCommand(AdoTemplate, info); bool bOutput = false; int i; if (info.TotalCount == 1)//进行分页? { bOutput = true; if (info.NamedQuery == null) { i = info.QueryObject.IndexOf("from", StringComparison.InvariantCultureIgnoreCase); string sCountSQL = string.Format("SELECT COUNT({0}) {1}", info.CountField , info.QueryObject.Substring(i));//from ... info.TotalCount = Convert.ToInt32(AdoTemplate.ExecuteScalar(CommandType.Text, sCountSQL, ps)); AdoAccessorHelper.BuildPagingSQL(AdoTemplate, info); //if (AdoTemplate.DbProvider.DbMetadata.ParameterNamePrefix == "?") //{ // mapper.Start = info.StartRecord; // mapper.Limit = info.PageSize; //} } } IList li = AdoTemplate.QueryWithRowMapper(info.NamedQuery == null ? CommandType.Text : CommandType.StoredProcedure , info.QueryObject + info.ToOrderBy(), mapper, ps); if (bOutput) AdoAccessorHelper.FetchOutputParameters(ps, info); return li; } [Obsolete] public IList ExecuteRowMapper(QueryInfo info, Type type) { IDbParameters ps = AdoAccessorHelper.PrepareCommand(AdoTemplate, info); ClassicRowMapper mapper = new ClassicRowMapper(type); bool bOutput = false; int i; if (info.TotalCount == 1)//进行分页? { bOutput = true; if (info.NamedQuery == null) { i = info.QueryObject.IndexOf("from", StringComparison.InvariantCultureIgnoreCase); string sCountSQL = string.Format("SELECT COUNT({0}) {1}", info.CountField , info.QueryObject.Substring(i));//from ... info.TotalCount = Convert.ToInt32(AdoTemplate.ExecuteScalar(CommandType.Text, sCountSQL, ps)); AdoAccessorHelper.BuildPagingSQL(AdoTemplate, info); if (AdoTemplate.DbProvider.DbMetadata.ParameterNamePrefix == "?") { mapper.Start = info.StartRecord; mapper.Limit = info.PageSize; } } } IList li = AdoTemplate.QueryWithRowMapper(info.NamedQuery == null ? CommandType.Text : CommandType.StoredProcedure , info.QueryObject + info.ToOrderBy(), mapper, ps); if (bOutput) AdoAccessorHelper.FetchOutputParameters(ps, info); return li; } public int ExecuteNonQuery(QueryInfo info) { IDbParameters ps = AdoAccessorHelper.PrepareCommand(AdoTemplate, info); int i = AdoTemplate.ExecuteNonQuery(info.NamedQuery == null ? CommandType.Text : CommandType.StoredProcedure , info.QueryObject, ps); if (info.TotalCount == 1) AdoAccessorHelper.FetchOutputParameters(ps, info); return i; } public DataSet ExecuteDataSet(QueryInfo info, bool closeSession = true) { IDbParameters ps = AdoAccessorHelper.PrepareCommand(AdoTemplate, info); DataSet ds = new DataSet(); bool bOutput = false; int i; if (info.TotalCount == 1)//进行分页? { bOutput = true; if (info.NamedQuery == null) { i = info.QueryObject.IndexOf("from", StringComparison.InvariantCultureIgnoreCase); if (i < 0) throw new ArgumentException("'from' clause is not found in 'CustomSQL'."); string sCountSQL = string.Format("SELECT COUNT({0}) {1}", info.CountField , info.QueryObject.Substring(i));//from ... info.TotalCount = Convert.ToInt32(adoTemplate.ExecuteScalar(CommandType.Text, sCountSQL, ps)); AdoAccessorHelper.BuildPagingSQL(AdoTemplate, info); } } i = AdoTemplate.DataSetFillWithParameters(ds, info.NamedQuery == null ? CommandType.Text : CommandType.StoredProcedure , info.QueryObject + info.ToOrderBy(), ps); if (bOutput) AdoAccessorHelper.FetchOutputParameters(ps, info); return ds; //IDbParameters ps = AdoAccessorHelper.PrepareCommand(AdoTemplate, info); //DataSet ds = new DataSet(); //bool bOutput = false; //int i; //if (info.TotalCount == 1)//进行分页? //{ // bOutput = true; // if (info.NamedQuery == null) // { // i = info.QueryObject.IndexOf("from", StringComparison.InvariantCultureIgnoreCase); // if (i < 0) // throw new ArgumentException("'from' clause is not found in 'CustomSQL'."); // string sCountSQL = string.Format("SELECT COUNT({0}) {1}", info.CountField // , info.QueryObject.Substring(i));//from ... // info.TotalCount = Convert.ToInt32(adoTemplate.ExecuteScalar(CommandType.Text, sCountSQL, ps)); // AdoAccessorHelper.BuildPagingSQL(AdoTemplate, info); // } //} //i = AdoTemplate.DataSetFillWithParameters(ds, info.NamedQuery == null ? CommandType.Text : CommandType.StoredProcedure // , info.QueryObject + info.ToOrderBy(), ps); //if (bOutput) // AdoAccessorHelper.FetchOutputParameters(ps, info); //return ds; } private AdoTemplate adoTemplate; public AdoTemplate AdoTemplate { get { if (adoTemplate == null) throw new Exception("'ClassicDAO'未被注入AdoTemplate属性,请检查Spring配置."); return adoTemplate; } set { adoTemplate = value; } } #endif #region IClassicDao 成员 public void SaveOrUpdateAll<T>(IList<T> list) where T : Framework.Domain.Entity { HibernateTemplate.Execute(delegate (ISession session) { if (session.Transaction.IsActive) { for (int i = 0; i < list.Count; i++) { Entity a = list[i] as Entity; if (a.State.New || string.IsNullOrEmpty(a.Id)) { session.Save(a); } else if (a.State.Deleted) { session.Delete(a); } else { session.Merge(a); } } session.Flush(); } else { using (var tx = session.BeginTransaction()) { try { int i = 0; foreach (Framework.Domain.Entity a in list) { if (a.State.New || string.IsNullOrEmpty(a.Id)) { session.Save(list[i]); } else if (a.State.Deleted) { session.Delete(list[i]); } else { session.Merge(list[i]); } i++; } tx.Commit(); } catch (Exception ex) { tx.Rollback(); throw ex; } finally { session.Close(); } } } return null; }); } public void SaveOrUpdateAll(IList list) { HibernateTemplate.Execute(delegate (ISession session) { if (session.Transaction.IsActive) { for (int i = 0; i < list.Count; i++) { Entity a = list[i] as Entity; if (a.State.New || string.IsNullOrEmpty(a.Id)) { session.Save(a); } else if (a.State.Deleted) { session.Delete(a); } else { session.Merge(a); } } session.Flush(); } else { using (var tx = session.BeginTransaction()) { try { int i = 0; foreach (Framework.Domain.Entity a in list) { if (a.State.New || string.IsNullOrEmpty(a.Id)) { session.Save(list[i]); } else if (a.State.Deleted) { session.Delete(list[i]); } else { session.Merge(list[i]); } i++; } tx.Commit(); } catch (Exception ex) { tx.Rollback(); throw ex; } finally { session.Close(); } } } return null; }); } public IStatelessSession GetStatelessSession() { _IStatelessSession = this.HibernateTemplate.SessionFactory.OpenStatelessSession(); return _IStatelessSession; } [Transaction(ReadOnly =true)] public ISession GetSession() { var sessionFactory = HibernateTemplate.SessionFactory; var session=sessionFactory.GetCurrentSession(); session.FlushMode=FlushMode.Auto; return session; } public ISession GetPerSession() { return this.HibernateTemplate.SessionFactory.OpenSession(); } private ISession _session = null; private IStatelessSession _IStatelessSession = null; #endregion } } web层配置文件,里面也涉及了sessionfactor currentsession在web层的调用需要指明sessionfactory 以及opensessioninview的配置请认真注意这两点 <configuration> <configSections> <sectionGroup name="elmah"> <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah"/> <section name="security" type="Elmah.SecuritySectionHandler, Elmah"/> <!--<section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" /> <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" /> <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah"/> <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah"/>--> </sectionGroup> <sectionGroup name="spring"> <section name="context" type="Spring.Context.Support.WebContextHandler, Spring.Web"/> <section name="parsers" type="Spring.Context.Support.NamespaceParsersSectionHandler, Spring.Core"/> </sectionGroup> <sectionGroup name="common"> <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging"/> </sectionGroup> <section name="databaseSettings" type="System.Configuration.NameValueSectionHandler, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/> <sectionGroup name="devExpress"> <section name="themes" type="DevExpress.Web.ThemesConfigurationSection, DevExpress.Web.v15.1" requirePermission="false"/> <section name="compression" type="DevExpress.Web.CompressionConfigurationSection, DevExpress.Web.v15.1" requirePermission="false"/> <section name="settings" type="DevExpress.Web.SettingsConfigurationSection, DevExpress.Web.v15.1" requirePermission="false"/> <section name="errors" type="DevExpress.Web.ErrorsConfigurationSection, DevExpress.Web.v15.1" requirePermission="false"/> </sectionGroup> </configSections> <elmah> <!--<errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="sql" />--> <errorLog type="Elmah.OracleErrorLog, Elmah" connectionStringName="ConnectionString"/> <security allowRemoteAccess="yes"/> </elmah> <common> <logging> <factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4Net"> <arg key="configType" value="FILE-WATCH"/> <arg key="configFile" value="~/Config/Log4Net.xml"/> </factoryAdapter> </logging> </common> <spring> <parsers> <parser type="Spring.Data.Config.DatabaseNamespaceParser, Spring.Data"/> <parser type="Spring.Transaction.Config.TxNamespaceParser, Spring.Data"/> </parsers> <context> <resource uri="~/Config/Dao2.xml"/> <resource uri="~/Config/Service.xml"/> <resource uri="~/Config/BLL.xml"/> <resource uri="~/Config/Log4Net.xml"/> <!-- <resource uri="~/Config/Dao.xml"/>--> </context> </spring> <databaseSettings> <add key="db.datasource" value="192.168.100.100"/> <add key="db.user" value="nethra"/> <add key="db.datasource2" value="192.168.100.100"/> <add key="db.password" value="nethra"/> <add key="db.database" value="hra"/> <add key="db.port" value="1521"/> <!--<add key="db.datasource" value="117.29.168.106"/> <add key="db.user" value="nethra"/> <add key="db.datasource2" value="117.29.168.106"/> <add key="db.password" value="nethra"/> <add key="db.database" value="hrarelease"/> <add key="db.port" value="1541"/>--> <!--<add key="db.datasource" value="192.168.140.128" /> <add key="db.user" value="nethra" /> <add key="db.datasource2" value="192.168.140.128" /> <add key="db.password" value="nethra" /> <add key="db.database" value="XE" /> <add key="db.port" value="1521" />--> <!--<add key="db.datasource" value="192.168.2.106" /> <add key="db.user" value="nethra" /> <add key="db.datasource2" value="192.168.2.106" /> <add key="db.password" value="nethra" /> <add key="db.database" value="XE" /> <add key="db.port" value="1521" />--> <!--<add key="db.datasource" value="192.168.1.10" /> <add key="db.user" value="nethra" /> <add key="db.datasource2" value="192.168.1.106" /> <add key="db.password" value="nethra" /> <add key="db.database" value="hrarelease" /> <add key="db.port" value="1521" />--> <!--<add key="db.datasourceSql" value="117.29.168.106"/> <add key="db.userSql" value="sa"/> <add key="db.passwordSql" value="haihui2013"/> <add key="db.databaseSql" value="Holworth_SC"/>--> </databaseSettings> <system.web> <globalization fileEncoding="utf-8" requestEncoding="utf-8" responseEncoding="utf-8"/> <pages theme="default" enableSessionState="true" validateRequest="false"> <controls> <add tagPrefix="asp" namespace="WebControls.Web.UI" assembly="WebControls"/> <add tagPrefix="asp" namespace="Trirand.Web.UI.WebControls" assembly="Trirand.Web"/> <!--<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />--> <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </controls> </pages> <authentication mode="Forms"> <forms name=".ADUAUTH" loginUrl="Login.aspx" protection="All"/> </authentication> <httpModules> <add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web"/> <remove name="FormsAuthentication"/> <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/> <add type="DevExpress.Web.ASPxHttpHandlerModule, DevExpress.Web.v15.1, Version=15.1.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" name="ASPxHttpHandlerModule"/> </httpModules> <trace enabled="false" requestLimit="10" pageOutput="true" traceMode="SortByTime" localOnly="true"/> <sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" timeout="20"/> <compilation debug="true"> <assemblies> <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Web.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="Microsoft.Build.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Management, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="DevExpress.Printing.v15.1.Core"/> <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Web.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="DevExpress.Web.ASPxThemes.v15.1"/> <add assembly="DevExpress.XtraReports.v15.1.Web"/> <add assembly="DevExpress.Web.v15.1"/> <add assembly="DevExpress.Data.v15.1"/> <add assembly="System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Runtime.Caching, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System.Web.ApplicationServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="Microsoft.Build.Utilities.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System.DirectoryServices.Protocols, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System.Web.RegularExpressions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/></assemblies> <buildProviders> <add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/> </buildProviders> </compilation> <httpHandlers> <remove verb="*" path="*.asmx"/> <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add verb="GET,HEAD" path="ScriptResource.axd" validate="false" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add verb="POST,GET,HEAD" path="error.axd" type="Elmah.ErrorLogPageFactory, Elmah"/> <add verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/> <add type="DevExpress.Web.ASPxHttpHandlerModule, DevExpress.Web.v15.1" verb="GET" path="DX.ashx" validate="false"/> </httpHandlers> </system.web> <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> </system.serviceModel> <appSettings> <add key="Spring.Data.NHibernate.Support.OpenSessionInViewModule.SessionFactoryObjectName" value="SessionFactory"/> <add key="COMMON_CFG" value="ConfigApp.config"/> <add key="NO_AUTO_CONFIG" value="1"/> <add key="DataBase" value="1"/> <add key="pageSize" value="30"/> </appSettings> <connectionStrings> <!--<add name="sql" connectionString="Integrated Security=false; Data Source=PANTECH-PCWINDSHADOWSS;Database=simpleframework;User ID=sa;Password=123;"/>--> <add name="ConnectionString" connectionString="Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST =192.168.2.252)(PORT = 1521))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME =hrarelease)));User Id=nethra;Password=nethra;" providerName="Oracle.DataAccess"/> </connectionStrings> <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4"> <providerOption name="CompilerVersion" value="v3.5"/> <providerOption name="WarnAsError" value="false"/> </compiler> </compilers> </system.codedom> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <modules> <remove name="ScriptModule"/> <add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web"/> <add name="OpenSessionInView" type="Spring.Data.NHibernate.Support.OpenSessionInViewModule, Spring.Data.NHibernate30"/> <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add type="DevExpress.Web.ASPxHttpHandlerModule, DevExpress.Web.v15.1" name="ASPxHttpHandlerModule"/> </modules> <handlers> <remove name="WebServiceHandlerFactory-Integrated"/> <remove name="ScriptHandlerFactory"/> <remove name="ScriptHandlerFactoryAppServices"/> <remove name="ScriptResource"/> <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="ScriptResource" verb="GET,HEAD" path="ScriptResource.axd" preCondition="integratedMode" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/> <add type="DevExpress.Web.ASPxHttpHandlerModule, DevExpress.Web.v15.1" verb="GET" path="DX.ashx" name="ASPxHttpHandlerModule" preCondition="integratedMode"/> </handlers> </system.webServer> <runtime> <assemblyBinding appliesTo="v2.0.50727" xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/> <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/> <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/> </dependentAssembly> </assemblyBinding> </runtime> <system.web> <!--<httpRuntime targetFramework="4.0" requestValidationMode="2.0"/>--> <httpRuntime maxRequestLength="2147483647" requestValidationMode="2.0"/> </system.web> <devExpress> <themes enableThemesAssembly="true" styleSheetTheme="" theme="" customThemeAssemblies=""/> <compression enableHtmlCompression="false" enableCallbackCompression="true" enableResourceCompression="true" enableResourceMerging="true"/> <settings doctypeMode="Xhtml" rightToLeft="false" embedRequiredClientLibraries="false" ieCompatibilityVersion="edge"/> <errors callbackErrorRedirectUrl=""/> </devExpress> </configuration>