2010-06-18 125 views
18

我使用@GeneratedValue(strategy = GenerationType.AUTO)在我的實體上生成ID。oracle上的休眠序列,@GeneratedValue(strategy = GenerationType.AUTO)

我現在不知道它是如何工作的,但在我的子表上,生成了遵循父順序的ID值。

//parent table 
@Entity 
@Table (name = "parent") 
public class Parent { 

    @Id 
    @GeneratedValue (strategy = GenerationType.AUTO) 
    @Column (name = "id") 
    private long id; 


    @OneToMany (cascade = {CascadeType.ALL}, fetch = FetchType.LAZY) 
    @JoinColumn (name = "parentId") 
    @ForeignKey (name = "FKparent") 
    private List<child> child; 

} 

//child table 
@Entity 
@Table (name = "child") 
public class Child { 

    @Id 
    @GeneratedValue (strategy = GenerationType.AUTO) 
    @Column (name = "id") 
    private long id; 
} 

在父級上插入的ID值更新序列。 孩子上插入的ID值,更新序列。 對於父代的下一個插入,序列...使用由子插入更新的值...

此批註不創建兩個序列,只有一個。這是正確的/預期的?

我插入我的實體吾道服務只使用entityManager.persist(parent);

回答

1

是的,這是正確的和預期。

您可以爲每個表創建單獨的序列,但恕我直言,這只是額外的代碼沒有實際的好處。

+0

若最終用戶看到該密鑰和由它被誤導「神經質」。不要告訴我,關鍵需要隱藏的用戶,這並不總是可能的... – Monoman 2012-02-27 18:54:35

+1

有沒有辦法保持ids恆定的時間和單調,沒有漏洞的序列,這並不殺可擴展性。我也沒有看到'jumpy'的有用定義以及爲什麼用戶需要unjumpy ID。 – 2012-02-28 06:48:24

44

這些註釋沒有創建兩個序列,只有一個。這是正確的/預期的?

這是預期的行爲。當使用@GeneratedValue(strategy = GenerationType.AUTO)時,JPA提供者將爲特定數據庫選擇合適的策略。就Oracle而言,這將是SEQUENCE,並且由於您沒有指定任何內容,Hibernate將使用一個名爲hibernate_sequence的單個全局序列。

這是正確的嗎?那麼,我不知道,這取決於你的需求。以防萬一,Oracle序列的默認最大值爲1E + 27或1,000,000,000,000,000,000,000,000,000。這對許多人來說已經足夠了現在

,能夠使用GenerationType.AUTO和靜止控制序列的名稱時,數據庫使用的序列:

@Id 
@GeneratedValue(strategy=GenerationType.AUTO, generator="my_entity_seq_gen") 
@SequenceGenerator(name="my_entity_seq_gen", sequenceName="MY_ENTITY_SEQ") 
private Long id; 
+4

Pascal,但是如果你想使用GenerationType.AUTO來允許像MySQL這樣的其他數據庫使用Identity插入,這將不起作用,不是嗎?因爲你手動指定了一個生成器 – lujop 2013-01-11 11:21:20

0
@Entity 
@Table(name = "table_seq") 
@SequenceGenerator(name= "NAME_SEQUENCE", sequenceName = "SEQ_ID", initialValue=1, allocationSize = 1) 
public class SeqEntity implements Serializable { 
    private static final long serialVersionUID = 1L; 

@Id 
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="NAME_SEQUENCE") 
private Long id; 

}