Discussions

EJB design: Idea for Unique Primary Keys

  1. Idea for Unique Primary Keys (4 messages)

    The issue of creating a unique primary key comes up often when speaking of EJBs. The problem is that autoincrementing schemes are db-specific, so other methods must be derived to build a unique id. Here's a simple method that seems to work:

      // Snippets from some ejbCreate() method
      BeanHome beanHome = (BeanHome) ctx.getEJBHome();
      id = beanHome.findAll().size();

    My question is this: can this guarantee a unique id, or can 2 create methods be fetching the size concurrently? What, if any, kind of transactions are needed to guarantee uniquness?

    Threaded Messages (4)

  2. Idea for Unique Primary Keys[ Go to top ]

    See the Patterns section for a resonable algorithm for guaranteeing unique keys.

    Dave Wolf
    Internet Applications Division
    Sybase
  3. Idea for Unique Primary Keys[ Go to top ]

    The extensive discussion in the patterns section actually prompted my question. I'm wondering if the very simple technique that I asked about could serve the same purpose.
  4. Idea for Unique Primary Keys[ Go to top ]

    The biggest negetive will be the performance of this. You need to do a table scan of an entire table just to get the next key id. Secondly there is nothing stopping what we call a Halloween scenario from happening. That is where another bean inserts a row while you are trying to do findAll. Now you can either skip a number, or have two beans get the same number of records and get duplicate keys.

    Dave Wolf
    Internet Applications Division
    Sybase
  5. Idea for Unique Primary Keys[ Go to top ]

    Sure - the easiest approach is to use 'cheating' stateless session bean (or beans if you require a pool), which allocate chunks of PKs from the database and dispense them. The cheating here is that SSBs have to remember the state (chunk and the position in it). I have this schema working in Weblogic and it performs just fine.