2013-10-19 97 views
0

簡單的問題NHibernate的定製IIdentifierGenerator我可以做這樣的事情:有交易

(我不知道用另一種方式這一點,因爲NHibernate的doesn't支持嵌套事務)

public class GetNextSequence : IIdentifierGenerator 
    { 
     public object Generate(NHibernate.Engine.ISessionImplementor session, object obj) 
     { 
      using (var nSession = SessionFactoryWrapper.SessionFactory.OpenSession()) 
      { 
       using(var tran = nSession.BeginTransaction(System.Data.IsolationLevel.Serializable)) 
       { 
        var update = nSession.CreateSQLQuery("update counter set last_one = last_one + 1 where item like :item"); 
        update.SetParameter("item", "account_contact.account_contact_id"); 

        update.ExecuteUpdate(); 

        var query = nSession.CreateSQLQuery("SELECT last_one FROM counter WHERE item LIKE :item"); 
        query.SetParameter("item", "account_contact.account_contact_id"); 
        var lastOne = query.UniqueResult(); 

        tran.Commit(); 
        return lastOne; 
       } 
      } 
     } 
    } 

或這是我不應該做的事情,如果有的話,爲什麼不呢?

+0

這非常看起來很像希洛。你不能用它來代替嗎? – Rippo

+0

是的,也許我需要使用這張表並增加計數器+1,我需要確保沒有人能讀取舊的計數器值! Hilo可能嗎? – makim

+0

是的,這正是hilo的功能,它爲您提供了額外的好處。您使用的映射類型是什麼? XML流利或通過代碼映射,我會發佈一個答案 – Rippo

回答

1

你可以嘗試這樣的事情

public class GetNextSequence : IIdentifierGenerator, IConfigurable 
    { 
     private string _item; 

     public object Generate(NHibernate.Engine.ISessionImplementor session, object obj) 
     { 
      using (var nSession = SessionFactoryWrapper.SessionFactory.OpenSession()) 
      { 
       using(var tran = nSession.BeginTransaction(System.Data.IsolationLevel.Serializable)) 
       { 
        var update = nSession.CreateSQLQuery("update counter set last_one = last_one + 1 where item like :item"); 
        update.SetParameter("item", _item); 

        update.ExecuteUpdate(); 

        var query = nSession.CreateSQLQuery("SELECT last_one FROM counter WHERE item LIKE :item"); 
        query.SetParameter("item", _item); 
        var lastOne = query.UniqueResult(); 

        tran.Commit(); 
        return lastOne; 
       } 
      } 
     } 

     public void Configure(NHibernate.Type.IType type, IDictionary<string, string> parms, NHibernate.Dialect.Dialect dialect) 
     { 
      parms.TryGetValue("item", out _item); 
     } 
    }