[英]Spring, JPA and Hibernate - id generation
Setup: Sprting, JPA and Hibernate as JPA provider. 设置:Sprting,JPA和Hibernate作为JPA提供程序。
We have two class hierarchies, one for questions and other one for answers. 我们有两个类层次结构,一个用于问题,另一个用于答案。 At the root of each hierarchy there is an abstract class, for example:
在每个层次结构的根部都有一个抽象类,例如:
@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();
}
and 和
@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;
}
}
in each hierarchy there are 3 concrete classes. 在每个层次结构中,都有3个具体的类。 We wanted to store them in database, for now we are using SQLite.
我们想将它们存储在数据库中,现在我们正在使用SQLite。
If I understand correctly this Inheritance strategy will create one table per concrete class. 如果我理解正确,则此继承策略将为每个具体类创建一个表。
Now, when I set up GeneratedValue strategy at auto I got errors, so I switched it to table. 现在,当我自动设置GeneratedValue策略时,出现了错误,因此我将其切换到表。 If I understand it correctly, for each table there will be different independent generation of ids.
如果我正确理解,对于每个表,将会有不同的独立ID生成。
But something strange happened. 但是有些奇怪的事情发生了。 I created simple testing code:
我创建了简单的测试代码:
QuestionUnit unit1=new OpenQuestion("4+4", new OpenQuestionAnswer("8"));
questionUnitDao.addQuestionUnit(unit1);
System.out.println(questionUnitDao.getQuestionUnit(OpenQuestion.class, 1).getQuestionContent());
the first question was inserted succesfully, but then I got an error that primary key should be unique, now when I insert something I get very large numbers as ids, for example 65536. 第一个问题被成功插入,但是随后我得到一个错误,即主键应该是唯一的,现在当我插入某些东西时,我会得到非常大的数字作为id,例如65536。
Why is it? 为什么?
You can add TableGenerator annotation in your both entities.See sample; 您可以在两个实体中添加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;
But don't forget to create ID_GEN table with two fields GEN_NAME and GEN_VAL in your database. 但是不要忘记在数据库中创建具有两个字段GEN_NAME和GEN_VAL的ID_GEN表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.