0

我想使用 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)    
    @PrimaryKeyJoinColumn
    private AnswerUnit correctAnswer;
...}


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

    @Id
    private int id;

    public abstract Object getAnswerContent();

    public abstract boolean isEqual(AnswerUnit otherAnswer);

    public int getId() {
        return id;
    }
}

我们有 OpenQuestion 和 OpenAnswer 作为实现。

我想要这样带有 OpenQuetions 的表将具有自动生成的主键,而带有 OpenAnswer 的表将具有与 OpenQuestion 表中的主键具有相同值的主键。

我尝试从这里遵循示例:http: //docs.jboss.org/hibernate/annotations/3.5/reference/en/html/entity.html part 2.2.5.1。一对一。

但是当我坚持 OpenQuestion 时,我得到了带有 columns 的表 OpenQuestion和带有id,的questionContentOpenQuestionAnswer idanswerContent但是 id 的值不匹配。

那么,我在哪里犯了错误?

4

2 回答 2

0

您在“OpenQuestion”中没有“CorrectAnswer”栏吗?
这应该是“OpenAnswer”中 ID 列的外键 -
即 - 这些应该是匹配的 ID 值。
如果您没有此列 - 我怀疑您的 JPA 映射中有某种错误。
编辑 - 对我自己 -
请添加 MappedSuperClass。在这里阅读它。

于 2012-08-13T15:02:32.103 回答
0

我不确定您要做什么,为什么从问题到答案的关系是一对一的?逻辑告诉我一个问题可以有很多答案(而且可能只有一个正确答案)。

使用这种方法,您不需要关心两个 id 是否相等,如果是这样,您应该有这样的模型:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class QuestionUnit {
    @Id ... private int id;
    @OneToMany private List<AnswerUnit> answers; //optional assuming there's a list of answers for every question
    @ManyToOne private AnswerUnit correctAnswer;

    public void setCorrectAnswer(AnswerUnit answer){
        if(answer.getQuestion().equals(this)){ //or maybe instead answer.setQuestion(this)
            this.correctAnswer = answer;
        }else{
            throw new RuntimeError("Answer does not belong to this question");
        }
    }

    //Other getter and setters
    //Override the "equals" method!!!
}


@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AnswerUnit {
    @Id private int id;
    @OneToMany private QuestionUnit question;

    public abstract Object getAnswerContent();    
    public abstract boolean isEqual(AnswerUnit otherAnswer); //should't you just overwrite the equals method in here?    
    //Other getter, setters, etc
}

然后使用它,如下所示:

QuestionUnit q = new OpenQuestion();
List<AnswerUnit> answers = new List<OpenAnswer>();

AnswerUnit a1 = new OpenAnswer();
AnswerUnit a2 = new OpenAnswer();
AnswerUnit a3 = new OpenAnswer();

a1.setQuestion(q);
a2.setQuestion(q);
a3.setQuestion(q);

//Also set the contents and other required info for the questions...

//And then associate the instances:
q.setAnswers(answers);
q.setCorrectAnswer(a3);

em.persist(q);

即使有公开和常规的答案,这也可以工作

于 2012-08-14T15:14:32.980 回答