I and John Jullion-Ceccarelli wrote a tutorial
about primary key generation in EJB 2.1. It was very pretty painful stuff, you should create table with appropriate data type column, use Object primary key and other. In EJB 3.0 is generation of PK different, it's easy to use. Let's go through all options that are for this in EJB 3.0.
Primary key you can define in Entity bean with @Id annotation. There are five options for GeneratorType: NONE, AUTO, IDENTITY, SEQUENCE and TABLE. First one is NONE, it means that application is responsible for generation of primary key. Next one is AUTO that leaves the job to the container. This strategy indicates that a persistence provider should pick up appropriate strategy according to the database. It means that you need not setup your id and container generates it. I would like to describe SEQUENCE and TABLE strategy in more details below. SEQUENCE or IDENTITY strategy use a database sequence or identity column. I will show this strategy for Oracle database. We need to create new sequence with this command:
CREATE SEQUENCE EMPL_ID INCREMENT BY 1 START WITH 100;
Then, this sequence can be used in entity bean like this:
The sequenceName attribute specifies name of sequnce object in database. For TABLE strategy we should create table in database where primary keys will be stored:
CREATE TABLE GEN_ID(
Then you can use this table in entity bean with TABLE generator strategy:
All attributes are very intuitive and can be guessed from this sample.
Generation of primary key in EJB 3.0 is simple, isn't it?