Use Sequence to generate Primary key in TopLink/EclipseLink (JPA)

 

TopLink/EclipseLink have an easy way of using database sequence to generate primary key of a table. Here is a snapshot of the JPA Entity class generated from existing database table by Netbeans

    @Id
    @Basic(optional = false)
    @Column(name = "ID", nullable = false, precision = 22)
    @SequenceGenerator(sequenceName="SEQUENCENAME_SEQ",name="OTHER_NAME")
    @GeneratedValue(generator="OTHER_NAME",strategy=GenerationType.SEQUENCE)
    private int id;

    
   
The lines in red indicate the code added manually after the JPA Entity class was created by Netbeans. The SEQUENCENAME_SEQ represents the name of the sequence object in the database. The OTHER_NAME is just an alias and this can be referred to by the GeneratedValue annotation. GeneratedValue tells the code to use database sequence as primary key. You may also add INCREMENT BY using allocationSize attribute to SequenceGenerator annotation.

For more advanced strategies check out :http://wiki.eclipse.org/EclipseLink/Examples/JPA/PrimaryKey

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s