Auto-generating Primary Keys

Written by Joseph Ottinger

Sequences are database-specific mechanisms to generate counters, but that's not very useful for EJBs, since they don't have to map to databases. That leaves EJB authors with the problem of generating unique identifiers for beans. 

Orion comes with a deployable EJB, in a file called "counter.jar". To use it, follow these steps:

  1. Deploy counter.jar in your application.xml, by adding the following line:
    <module><ejb>counter.jar</ejb></module>
  2. Add an EJB reference to your web.xml that looks something like:
    <ejb-ref>
    <ejb-ref-name>ejb/Counter</ejb-ref-name>
    <ejb-ref-type>Entity</ejb-ref-type>
    <home>com.evermind.ejb.CounterHome</home>
    <remote>com.evermind.ejb.Counter</remote>
    </ejb-ref>
  3. In the code where you need a handy unique counter (an EJB create() method, perhaps?), you can use the following function call, which uses a utility class inside counter.jar:
    com.evermind.ejb.CounterUtils.getNextID("java:comp/env/ejb/Counter", "mybeanname")

Note that the same counter deployment can be used for any unique counter; all you would do is specify a different "bean name" (actually just a unique identifier of some kind) in the getNextID() function call.

Copyright © 2007 IronFlare AB