2012-08-10 66 views
0

設置:Sprting,JPA和Hibernate作爲JPA provider。Spring,JPA和Hibernate - id generation

我們有兩個類層次結構,一個用於提問,另一個用於答案。在每個層次的根有一個抽象類,例如:

@Entity 
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) 
public abstract class QuestionUnit { 

    @Id 
    @GeneratedValue(strategy = GenerationType.TABLE) 
    private int id; 
    @OneToOne(cascade = CascadeType.ALL) 
    private AnswerUnit correctAnswer; 

    public QuestionUnit(AnswerUnit correctAnswer) { 
     this.correctAnswer = correctAnswer; 
    } 

    public void setCorrectAnswer(AnswerUnit correctAnswer) { 
     this.correctAnswer = correctAnswer; 
    } 

    public AnswerUnit getCorrectAnswer() { 
     return this.correctAnswer; 
    } 

    public int getId() { 
     return id; 
    } 

    public abstract Object getQuestionContent(); 
} 

@Entity 
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) 
public abstract class AnswerUnit { 

    @Id 
    @GeneratedValue(strategy = GenerationType.TABLE) 
    private int id; 

    public abstract Object getAnswerContent(); 

    public abstract boolean isEqual(AnswerUnit otherAnswer); 

    public int getId(){ 
     return id; 
    } 
} 
在各個等級

有3具體類。我們希望將它們存儲在數據庫中,現在我們正在使用SQLite。

如果我理解正確,這個繼承策略將爲每個具體類創建一個表。

現在,當我在自動設置GeneratedValue策略時出現錯誤,因此我將它切換到了表格。如果我理解正確,每個表格都會有不同的獨立代碼。

但是發生了一些奇怪的事情。我創建了簡單的測試代碼:

QuestionUnit unit1=new OpenQuestion("4+4", new OpenQuestionAnswer("8")); 
questionUnitDao.addQuestionUnit(unit1); 
System.out.println(questionUnitDao.getQuestionUnit(OpenQuestion.class, 1).getQuestionContent()); 

的第一個問題是插入成功,但後來我得到了一個錯誤,主鍵應該是唯一的,現在當我插入的東西,我得到非常大的數字作爲標識,例如65536。

爲什麼?

+0

關於大生成的ID,請參閱[這個問題](http://stackoverflow.com/questions/2892355/jpa-generatedvalue-with-generationtype-table-does-a-big-jump-after-jvm-restart ) – siebz0r 2012-08-11 10:34:23

+0

感謝或鏈接,這是因爲Hilo算法用於id生成。 – Andna 2012-08-11 10:54:38

+0

當你將它設置爲AUTO時有什麼錯誤? 另請注意,使用基本類型作爲ID是不鼓勵的。 – 2012-08-12 12:49:15

回答

0

您可以在兩個實體中添加TableGenerator註釋。

@Id 
    @TableGenerator(name = "QuestionUnitGen", 
    table = "ID_GEN", 
    pkColumnName = "GEN_NAME", 
    pkColumnValue = "QuettionUnit_Gen", 
    valueColumnName = "GEN_VAL", 
    initialValue = 0, 
    allocationSize = 100 
) 
    @GeneratedValue(strategy = GenerationType.TABLE, generator = "QuestionUnitGen") 
    private int id; 

但是不要忘記在數據庫中創建兩個字段GEN_NAME和GEN_VAL的ID_GEN表。