using System; using System.Data; using System.Data.SqlClient; using System.Runtime.CompilerServices; using System.Collections.Generic; using System.Collections; using System.Text; using NHibernate.Id; using NHibernate.Engine; using NHibernate.SqlCommand; using NHibernate.SqlTypes; using NHibernate.Type; using NHibernate.Util; using NHibernate.Dialect; using NHibernate.Mapping; namespace HYLQ.Core.Domain { class StreamGenerator : IPersistentIdentifierGenerator, IConfigurable { /**////<summary></summary> publicconststring ObjectNameTarget ="ObjectName"; publicconststring procNameTarget ="ProcedureName"; privatestring objectName; privatestring procName ="usp_GetID"; privatelong next; private System.Type returnClass; /**////<summary> /// ///</summary> ///<param name="type"></param> ///<param name="parms"></param> ///<param name="d"></param> publicvoid Configure(IType type, IDictionary parms, Dialect d) { objectName = parms[ObjectNameTarget] asstring; if (parms[procNameTarget] !=null) { procName = parms[procNameTarget] asstring; } returnClass = type.ReturnedClass; } /**////<summary> /// ///</summary> ///<param name="session"></param> ///<param name="obj"></param> ///<returns></returns> [MethodImpl(MethodImplOptions.Synchronized )] publicobject Generate(ISessionImplementor session, object obj) { if (objectName !=null) { getNext(session); } return IdentifierGeneratorFactory.CreateNumber(next, returnClass); } privatevoid getNext(ISessionImplementor session) { SqlConnection conn = (SqlConnection)session.Factory.OpenConnection(); SqlCommand qps = conn.CreateCommand(); qps.CommandText = procName; qps.CommandType = CommandType.StoredProcedure; qps.Parameters.Add(new SqlParameter("@ObjectName", SqlDbType.VarChar,10)); qps.Parameters["@ObjectName"].Value = objectName; try { next =int.Parse(qps.ExecuteScalar().ToString()); } catch { throw; } finally { session.Factory.CloseConnection( conn ); } } /**////<summary> /// ///</summary> ///<param name="dialect"></param> ///<returns></returns> publicstring[] SqlCreateStrings(Dialect dialect) { returnnewstring[0]; } /**////<summary> /// ///</summary> ///<param name="dialect"></param> ///<returns></returns> publicstring SqlDropString(Dialect dialect) { returnnull; } /**////<summary></summary> publicobject GeneratorKey() { return objectName; } } }
这里是调用一个存储过程来生成流水号的。 存储过程和表的定义如下:
--流水号 createtable Stream ( ObjectName varchar(10) notnull, --对象名 MaxID intnotnull, --流水号 primarykey(ObjectName) ) go --流水号发生器 ifexists(select*from sysobjects where type='p'and name='usp_GetID') dropproc usp_GetID go createproc usp_GetID ( @ObjectNamevarchar(10) --对象名 ) as begin declare@MaxIDint SET NOCOUNT ON ifexists(select*from Stream where ObjectName=@ObjectName) begin select@MaxID=MaxID from Stream where ObjectName=@ObjectName update Stream set MaxID=MaxID+1where ObjectName=@ObjectName end else begin set@MaxID=1 insertinto Stream values(@ObjectName,2) end select@MaxIDas MaxID end go