Sequence beans: auto-increment of primary key fields
An auto-incremet of your primary key field whenever a new record is inserted, is a feature commonly found in many databases (e.g., the auto_increment of MySQL, the
identity field in Hypersonic SQL or the sequence in Oracle). If you want such a feature for your entity beans, a sequence (generator) bean may offer the solution you are looking for.
A J2EE container can create the database tables in an empty database at deployment, including the references between them (using CMR fields). But how do you obtain an auto-increment feature? Sequence beans is a EJB pattern that allows for such a feature. Avoiding the discussion whether table creation by the container is really useful (i.e. database independence), and avoiding the discussion whether sequence beans are the most elegant solution (and above all, whether you should use EJBs at all), I’ll present here an example reworked for JBoss and Xdoclet.
Searching with Google I found this interesting discussion on the JOnAS users mail archive. This reply was very interesting, since it contained a link to a JAR containing an example. Although the issues raised by the author are outdated (“… it depends on reuse of pooled stateless session beans, a feature that is currently not supported by Jonas (as they told me it will be supported in the next release – end of September 2000)…”), the example was enough to let me easily refactor it for JBoss and Xdoclet.
The solution consists of a Sequence entity bean, that is accessible only via its associated SequenceGenerator stateless session bean (SLSB). Note that this SLSB does contain state, but is is state that is not associated to the client. According to the EJB specs, this is allowed.
The state of the counter is made persistent with the Sequence bean in the database. To prevent a performance bottleneck if the sequence generator is needed frequently, the state of the counter is persisted every
BLOCK_SIZE times only. Meanwhile, the SequenceGenerator SLSB caches the sequence last value (and we understand the reason for the need for pooled SLSBs). The
BLOCK_SIZE parameter can be configured in the deployment descriptor.
No related posts.