views:

295

answers:

2

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).

+1  A: 

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.

Michael Maddox
http://fabiomaulo.blogspot.com/2009/02/nh210-generators-behavior-explained.html
Quintin Par
@Quintin - That blog post doesn't really tell me anything I didn't already know. I'm not sure why you chose that as a comment to my answer?
Michael Maddox
A: 

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'"));
        }
     }
dmonlord
@dmonlord, Having maxLo set to 0 pretty much removes the advantage of using hilo in the first place. You will end up with a lot of network traffic this way and you are probably a lot better of using db-generated id's.
Mattias Jakobsson
I know, but that's what he wants. There probably isn't any good alternative to this if you don't want to implement your own generator.
dmonlord
@dmonlord, I know there isn't a alternative. I just pointed that out as the reason you use hilo (or any client generated id) is because you want less network traffic. With your solution you will end up with more network traffic.
Mattias Jakobsson