简体   繁体   English

没有NHibernate的NHibernate Hilo序列

[英]NHibernate Hilo Sequence without NHibernate

I have one application which uses NHibernate to save entities to a database, and it uses the HiLo generate of NHibernate to create the id's. 我有一个应用程序使用NHibernate将实体保存到数据库,它使用HiLo生成的NHibernate来创建id。 I have another application which I need to save data to the same table, however in this application, I'm not using NHibernate. 我有另一个应用程序,我需要将数据保存到同一个表,但是在这个应用程序中,我没有使用NHibernate。 Is there a simple way to use HiLo without adding reference to NHibernate and mapping files? 有没有一种简单的方法来使用HiLo而不添加对NHibernate和映射文件的引用?

<id name="EntityId" unsaved-value="0" >
    <column name="EntityId" sql-type="int" not-null="true" />
    <generator class="hilo">
    <param name="table">hibernate_unique_key</param>
        <param name="column">next_hi</param>
        <param name="max_lo">1000</param>
    </generator>
</id>

Update: I created a new method to get the next id which I believe has the same behavior as the NHibernate HiLo sequence. 更新:我创建了一个新方法来获取下一个id,我相信它具有与NHibernate HiLo序列相同的行为。 I'm not putting any locks on the database, so if this were a high frequency table that I was inserting to, it could be an issue, but for very low frequency, there is a very low possibility that there may be a concurrency issue. 我没有对数据库进行任何锁定,因此如果这是我插入的高频表,则可能是一个问题,但是对于非常低的频率,可能存在并发问题的可能性很小。 。

/// <summary>
/// Gets the next entity id.
/// </summary>
/// <returns></returns>
public static int GetNextAvailableEntityId()
{
    int max_lo = 1000;
    int nextHi = DefaultContext.Database.SqlQuery<int>("select next_hi from hibernate_unique_key").Single();
    int nextRangeStart = max_lo * nextHi;
    int currentMax = DefaultContext.Database.SqlQuery<int>("SELECT MAX(entityid) FROM Entities").Single();

    if (currentMax < nextRangeStart)
    {
        return currentMax + 1;
    }
    else
    {
        DefaultContext.Database.ExecuteSqlCommand("update hibernate_unique_key set next_hi = next_hi + 1");
        return nextHi;
    }
}

If in doubt, take a look at NH's code to be sure that you implement it correctly. 如果有疑问,请查看NH的代码,以确保您正确实现它。

It is something like this: 它是这样的:

  • open a separate transaction, increment and read the next high value, commit 打开一个单独的事务,递增并读取下一个高值,提交
  • create 1000 ids by next_high * 1000 + x 通过next_high * 1000 + x创建1000个ID
  • when you run out of ids, start again 当你用完ids时,重新开始

You can create a single instance of an id generator for all transaction of the same process. 您可以为同一进程的所有事务创建一个id生成器的单个实例。 Make sure that your id generator is thread safe. 确保您的id生成器是线程安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM