Fork me on GitHub

Programming Design Notes

使用 JPA 自動產生 ID

| Comments

以 PostgreSQL 為例。

首先先在 PostgreSQL 內新增一個 Sequence 和 Table。

User ID Sequence:
CREATE SEQUENCE user_id_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 1
CACHE 1;

User Table:
CREATE TABLE "user"
(
uid integer NOT NULL DEFAULT nextval('user_id_seq'::regclass),
username character varying(255) NOT NULL,
"password" character varying(255) NOT NULL,
CONSTRAINT user_pk PRIMARY KEY (uid)
)
WITH (
OIDS=FALSE
);

然後新增一個 Entity class。

User entity:
package com.blogspot.lawpronotes.entity;

import java.io.Serializable;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

@Entity
@Table(name = "user", schema = "public")
public class User implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "USER_UID_GENERATOR")
@SequenceGenerator(name = "USER_UID_GENERATOR", sequenceName = "user_id_seq", allocationSize = 1)
@Column(name = "uid")
private Integer uid;

@Basic
@Column(name = "username", nullable = false, unique = true)
private String username;

@Basic
@Column(name = "password", nullable = false, unique = false)
private String password;

public User() {
}

public Integer getUid() {
return this.uid;
}

public void setUid(Integer uid) {
this.uid = uid;
}

public String getName() {
return this.username;
}

public void setName(String username) {
this.username = username;
}

public String getPassword() {
return this.password;
}

public void setPassword(String password) {
this.password = password;
}

}

其中的關鍵:
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "USER_UID_GENERATOR")
@SequenceGenerator(name = "USER_UID_GENERATOR", sequenceName = "user_id_seq", allocationSize = 1)

GeneratedValue 的 strategy 是 GenerationType.SEQUENCE,即是不斷地加同一個數值,達到一致。而 generator 即是數值產生器的名稱,數值產生器即是 SequenceGenerator,SequenceGenerator 的 sequenceName 要跟資料庫內的 sequence 名稱一樣,因為是靠資料庫內的 sequence 產生數值的, allocationSize 即是每次將數值加多少,因為資料庫內的 sequence 設定了每次加 1 ,allocationSize 也要是 1 才行,系統預設的 allocationSize 是 50。現在應該可以自動產生 ID 了。

相關書籍: Pro JPA 2: Mastering the Java™ Persistence API (Expert's Voice in Java Technology)Pro EJB 3: Java Persistence APIPostgreSQL 8.4 Official Documentation - Volume V. Internals and Appendixes