0

简单的问题我可以做这样的事情:

(我不知道另一种方法,因为 NHibernate 不支持嵌套事务)

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;
                }
            }
        }
    }

或者这是我不应该做的事情,如果是这样,为什么不呢?

4

1 回答 1

2

你可以试试这样的

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);
        }
    }
于 2014-08-14T11:48:06.523 回答