Wednesday, June 15, 2011

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

No comments:

Post a Comment

Thank you for your feedback