NHibernate Hilo Sequence without NHibernate

I have one application that uses NHibernate to store entities in a database and uses the HiLo generator for NHibernate to create an identifier. I have another application that I need to save data to the same table, however in this application I do not use NHibernate. Is there an easy way to use HiLo without adding a link to NHibernate and mapping files?

<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 identifier, which I believe has the same behavior as the NHibernate HiLo sequence. I do not put any locks on the database, so if it were a high frequency table I inserted into, this might be a problem, but for a very low frequency there is a very low probability that there might 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; } } 
+4
source share
1 answer

If in doubt, look at the NH code to make sure you implement it correctly.

This is something like this:

  • open a separate transaction, increase and read the next high value, commit
  • create 1000 identifiers next_high * 1000 + x
  • when you run out of identifiers, start again

You can create one instance of the id generator for all transactions of the same process. Make sure your id generator is thread safe.

+3
source

All Articles