2014-02-08 37 views
5

我有使用產生的值休眠@SequenceGenerator不是全球

@Entity 
@SequenceGenerator(allocationSize = 1, initialValue = 1000, name = "idgen") 
public class Ent1 { 
    @Id 
    @GeneratedValue(generator = "idgen") 
    private Long id; 

    ... 
} 

@Entity 
public class Ent2 { 
    @Id 
    @GeneratedValue(generator = "idgen") 
    private Long id; 

    ... 
} 

的問題是,如果不把線

@SequenceGenerator(allocationSize = 1, initialValue = 1000, name = "idgen") 

實體我得到了兩個實體類錯誤:

Caused by: org.hibernate.AnnotationException: Unknown Id.generator: idgen 

But the JPA spec says that the scope of the @SequenceGenerator is 'global' and can be reused across entities.

我錯過了什麼?

回答

1

這似乎是Hibernate JPA實現中的一個錯誤,因爲它的工作方式與EclipseLink JPA實現(我已經測試過)相同。對於Hibernate,只有在使用orm.xml(假設您使用的是JPA EntityManager)在應用程序級聲明SequenceGenerator時,它才起作用。如果你還沒有一個orm.xml,它會在你的persistence.xml旁邊。

這裏的orm.xml中宣佈序列發生器的一個例子:

<?xml version="1.0" encoding="UTF-8"?> 
<entity-mappings 
    xmlns="http://java.sun.com/xml/ns/persistence/orm" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd" 
    version="2.0"> 

    <sequence-generator name="idgen" allocation-size="1" initial-value="1000" /> 

</entity-mappings> 

那麼你不必申報每班SequenceGenerator。

+0

我試着將@SequenceGenerator添加到package-info.java中,但後來發現編譯器錯誤,說這種類型的註釋在這裏不適用。 –

+0

package-info.java在Eclipse中編譯時工作,但我沒有嘗試過使用javac,現在我發現這是無效的(有趣的是Eclipse允許這樣做)。相反,您必須使用orm.xml來聲明序列生成器。看到我更新的答案。 – neildo

+0

也會有一種方法來覆蓋默認sequencegenerator,所以生成的值不需要每個類中的顯式引用? – Cloud

0

以下部分規範對我來說確實很陌生。

The scope of the generator name is global to the persistence unit (across all generator types).

你做我會解釋它:發電機可以在一個位置可以指定,並且同一個持久單元上的任何地方重用。就好像現在的Hibernate實現沒有考慮到這個句子。

是否有任何JPA/Hibernate規範專家可以幫助解釋此句子?