Quintin Par
Quintin Par

Reputation: 16252

Nhibernate id’s with sequential one step incremented id’s (alternatives to HiLo)

How do I instruct Nhibernate to generate sequential one step primary keys, like the sql generated ones?

The current HiLo algorithm generates keys like 4001 then 5010, 6089 etc. I understand that this is to manage multiple app servers etc. But I don’t have that problem.
I need nhibernate to pick up the highest record set value during startup (say 15) and then generate the next record with primary key 16(very much like generated id’s from sql’s side).

Upvotes: 2

Views: 1241

Answers (2)

dmonlord
dmonlord

Reputation: 1390

Create table:

CREATE TABLE `seq` (
  `ID` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `HI` bigint(20) unsigned NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `seq` VALUES ('COMMENT', '0');
INSERT INTO `seq` VALUES ('POST', '0');
INSERT INTO `seq` VALUES ('USER', '0');

Add mappings like this with FluentNHbiernate:

    public class Comment_Map : ClassMap<Comment>
    {
        public Comment_Map()
        {
            Table("COMMENT");

            Id(x => x.ID, "ID").GeneratedBy.HiLo("SEQ", "HI", "0", o => o.AddParam("where", "ID = 'COMMENT'"));
        }
     }

Upvotes: 1

Michael Maddox
Michael Maddox

Reputation: 12489

Why do you need/expect NHibernate to do this for you?

It's hard for NHibernate to provide a generic solution for scenarios like this as the requirements can vary ever so slightly, but since you exactly know your particular constraints, it should be relatively straight-forward for you to provide your own solution (using manually assigned ids).

On application startup, query the database and get the current max id value. Increment that value every time you do an insert.

Upvotes: 1

Related Questions