This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Servlets and the fly likes key-generator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "key-generator" Watch "key-generator" New topic


Elahe Shafie
Ranch Hand

Joined: Dec 12, 2001
Posts: 291
I have heard a bit about primary key generators lately on the list.I am interested in writing a simple one. What are the goals a good generator should accomplish? Any pitfalls to watch out for? Maybe someone could point out some good resources on the web?

Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 16019

A primary key generator is "good" when it generates unique keys. Otherwise it's defective. The most common cause of failure is in multi-threaded systems where the process isn't atomic and the same key can be generated twice because the internal value wasn't updated before another request came in.
The easiest generation technique is just to use an integer and increment it for each new row added to the table. Many DBMS's have the ability to do this for you automatically.
When working with CMP EJB's, there's a problem with this, though, since CMP EJBs expect ALL values for a newly-created EJB to be supplied by the constructor and not acquired from the DBMS. TO get around this, I use a special EJB that has a "createNewKey()" method. Because it's an EJB, the atomicity of the operation is ensured by the EJB transaction mechanism.

Customer surveys are for companies who didn't pay proper attention to begin with.
I agree. Here's the link:
subject: key-generator