设置:Sprting、JPA 和 Hibernate 作为 JPA 提供者。
我们有两个类层次结构,一个用于问题,另一个用于答案。在每个层次结构的根部都有一个抽象类,例如:
@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。
如果我理解正确,这个继承策略将为每个具体类创建一个表。
现在,当我在 auto 设置 GeneratedValue 策略时出现错误,所以我将其切换到 table。如果我理解正确,对于每个表都会有不同的独立代号。
但是奇怪的事情发生了。我创建了简单的测试代码:
QuestionUnit unit1=new OpenQuestion("4+4", new OpenQuestionAnswer("8"));
questionUnitDao.addQuestionUnit(unit1);
System.out.println(questionUnitDao.getQuestionUnit(OpenQuestion.class, 1).getQuestionContent());
第一个问题已成功插入,但后来我得到一个错误,即主键应该是唯一的,现在当我插入一些东西时,我得到非常大的数字作为 id,例如 65536。
为什么?