Hibernate 中 sequence 和 identity 的區別
Hibernate 或 JPA 支援 4 種不同的主鍵生成器。這些生成器用於在資料庫中插入行時生成主鍵。以下是主鍵生成器 −
- GenerationType.AUTO
- GenerationType. IDENTITY
- GenerationType.SEQUENCE
- GenerationType.TABLE
GenerationType. IDENTITY − 在 identity 中,資料庫負責自動生成主鍵。插入一行而不為 ID 指定值,並在插入行後,向資料庫請求最後生成的 ID。Oracle 11g 不支援 identity 主鍵生成器。此功能在 Oracle 12c 中受支援。
GenerationType. SEQUENCE − 在 sequence 中,我們首先向資料庫請求序列的下一組值,然後使用返回的序列 ID 插入行。
序號 | 關鍵點 | GenerationType. IDENTITY | GenerationType.SEQUENCE |
---|---|---|---|
1 | 基礎 | 資料庫負責自動生成主鍵 | 我們首先向資料庫請求序列的下一組值,然後使用返回的序列 ID 插入行。 |
2 | 效能 | 它比 sequence 主鍵生成器快 | 它比 identity 主鍵生成器略慢 |
3 | 資料庫支援 | Oracle 11g 不支援 identity 主鍵生成器 | Oracle 11g 支援 SEQUENCE 主鍵生成器 |
GenerationType.IDENTITY 示例
@Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Integer id; String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
GenerationType.SEQUENCE 示例
@Entity public class User { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) Integer id; String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
廣告