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