Generating Primary keys in JPA

Every entity that is mapped to a relational database must have a mapping to a primary key in the table.
Primary Key Types

JPA provides the Table, Sequence, Auto, and Identity strategies for generating primary keys.

Table Strategy

With this strategy the persistence engine uses a relational database table from which the keys are generated. This strategy has the advantage of portability; we can use it with any relational database.

Sequence Strategy

Some databases, such as Oracle, have a built-in mechanism called sequences for generating keys. To invoke such a sequence we need to use the @SequenceGenerator annotation. For example:
 
@SequenceGenerator(name="USER_SEQ", sequenceName="USER_SEQUENCE")

Identity Strategy

Some databases, such as Microsoft SQL Server, use an identity column for generating keys. To use this we specify the IDENTITY strategy in the @GeneratedValue annotation:
 
@GeneratedValue(strategy=GenerationType.IDENTITY)
Note that there is no generator element that we have for the Table and Sequence strategies.

Auto Strategy

The final strategy is the AUTO strategy. With this strategy the persistence engine selects the strategy. In the case of GlassFish the TABLE strategy is selected. We can specify an AUTO strategy either explicitly:
 
@GeneratedValue(strategy=GenerationType.AUTO)
or implicitly:
@GeneratedValue
as the default strategy is AUTO.

Examples

Table ids for primary keys
----------------------
| pk_name | pk_value |
----------------------
| user_pk |         3|
----------------------


package data;
import javax.persistence.*;
@Entity
public class User {
    private int id;
    private String userid = "";
    private String password = "";
    private String role = "default";
    @Id
    @TableGenerator(name="user_pk",table="ids",pkColumnName="pk_name",valueColumnName="pk_value", pkColumnValue="user_pk")
    @GeneratedValue(strategy=GenerationType.IDENTITY,generator="user_pk")
    public int getId() {
        return id;
    }
    public void setId(int id) {

        this.id = id;
    }
    public String getUserid() {
        return userid;
    }
    public void setUserid(String userid) {
        this.userid = userid;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }
    public String toString() {

        return "User [password=" + password + ", role=" + role + ", userid="

                + userid + "]";
    }
}






No comments:

Popular Posts