Primary key generation in EJB 3.0blo
By pblaha on Dec 21, 2005
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:
@Id(generate=GeneratorType.SEQUENCE, generator="EMPL_GEN") @SequenceGenerator(name="EMPL_GEN",sequenceName="EMPL_ID")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( GEN_KEY VARCHAR(20), GEN_VALUE INTEGER, PRIMARY KEY(GEN_KEY))Then you can use this table in entity bean with TABLE generator strategy:
@Id(generate=GeneratorType.TABLE,generator="ORDER_GEN") @Column(name="ID") @TableGenerator(name="ORDER_GEN",pkColumnName="GEN_KEY", pkColumnValue="ORDER_ID",allocationSize=1, initialValue=1,valueColumnName="GEN_VALUE", table=@Table(name="GEN_ID"))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?