>For bean managed persistance you would simply use the functions that
>your DBMS provides, like sequences or auto-increased columns. But how do
>I do this with CMP beans? In books and example code everyone avoids the
>subject entirely, with
>create(int id)
>as the creation method.
Annoyingly enough, most EJB resources tend to avoid this subject. Wish they
wouldn't.
>A solution I've seen suggested is to use a separate session bean to
>generate unique integers, but they are generally a mess to implement and
>use. So what I'm looking for is something better than that.
There are 2 main approaches 2 generating IDs. Firstly you could use the
internal features of your database - many db's support SEQUENCES. This
solution seems fairly simple and elegant but using a db specific approach
can cause problems if you later decide to switch databases.
The preferred way to generate ID's is using a session bean and an entity
bean. The entity uses a reference to the table or bean name as a primary
key, and has a second field which stores the next id to use for that table.
The session bean is used as a wrapper around the entity to easily request
the next id per table.
In fact, updating the entity every time a new id is needed can be quite a
cumbersome and inefficient process, so a HIGH/LOW strategy is more
appropriate. Briefly, this is where the session bean is stateful and
instead of requesting and incrementing the entity each time an id is
required, a block of id's (eg: 20) are requested from the entity (which
then increments the count by that number) and the session counts out each
id until the block runs out, at which point it requests another block.
Multiple sessions can be used and each session will count with a seperate
block. Concurrent access can be handled by catching transaction exceptions
and trying again.
The drawbacks to this is that the id's in the db table are not guaranteed
to be in order and there may be some gaps if a session is destroyed before
it uses all of it's block of ids. The main advantage is that you will not
be tied in to any particular db.
There's a nice little paper that may be of use that describes this method
(although it has nothing to do with Java or EJB's):
http://www.ambysoft.com/mappingObjects.html
-Joe Walnes