views:

150

answers:

1

I am using hibernate's "increment" generator to generate my auto increment Id's. This was working fine until I had to add another application which also uses the "increment" generator to generate new id's. I realised there is a catch with the increment generator:

"generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. Do not use in a cluster."

Is there any way to deal with this using hibernate? Or will I have to write additional code to lock the table, check the db for max Id (and then increment it) and finally release the lock? Using one hibernate configuration is not an option. Also I can not add the auto_increment option to the db table because we have more than one key on the table.

Any suggestions are welcome, I am guessing this is a common problem.

+3  A: 

There are several other generators which may give you what you need:

  • hilo uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database.
  • uuid: uses a 128-bit UUID algorithm to generate identifiers of type string that are unique within a network (the IP address is used). The UUID is encoded as a string of 32 hexadecimal digits in length.

I'd recommend taking a look at hi/lo.

Also I can not add the auto_increment option to the db table because we have more than one key on the table.

I find this statement confusing - you cannot have one column be auto-incrementing if the primary key of the table uses more than one column?

Why would you have a primary key of more than one column where one of the columns is unique anyway - this makes it impossible to ever have more than one value for the id field, thus negating the purpose of a compound PK.

matt b
Thanks for the response. It appears like I'l have to create another table for this algorithm to store the hi value. We decided to go with the an SP. Regarding the primary key, I just simplified the question here. The id does not always auto increment. We are only testing it right now.
Rag
sometimes over-simplifying a question makes it confusing :)
matt b