1

我正在尝试映射 3 个实体:问题、答案和 QuestionDisplayRule。Question 有很多 Answers 和很多 QuestionDisplayRules,每一个都属于一个 Question。QuestionDisplayRule 有一个问题、一个答案和一个带有字符串值的字段。QuestionDisplayRule 的 db 表如下所示:

create table question_display_rule(
    question_id int, 
    answer_id int, 
    answer_value varchar(128)
);

自然而然,question_id 和 answer_id 就是PK。

JPA 映射如下所示:

@Embeddable
public class QuestionDisplayRulePK implements Serializable {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="question_id", insertable = false, updatable = false)
    private Question question;

    @ManyToOne
    @JoinColumn(name = "answer_id", insertable = false, updatable = false)
    private Answer answer;
}

@Entity
@Table(name = "question_display_rule")
public class QuestionDisplayRule implements Serializable {

    @EmbeddedId
    private QuestionDisplayRulePK id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="question_id", insertable = false, updatable = false)
    private Question question;

    @ManyToOne
    @JoinColumn(name = "answer_id", insertable = false, updatable = false)
    private Answer answer;

    @Column(name="answer_value")
    private String answerValue;

}

问题是如果我在数据库中手动添加记录但不会保存它们,它会很好地加载 QuestionDisplayRules。没有错误,没有什么..

测试代码:

    QuestionDisplayRulePK qPK = new QuestionDisplayRulePK();
    qPK.setQuestion(q);
    qPK.setAnswer(a);

    QuestionDisplayRule qr = new QuestionDisplayRule(qPK, "Yes");
    qr.setAnswerValue("whateva..");

    ....
    // DAO code looks like: getSession().saveOrUpdate(qr);

有任何想法吗?谢谢!

4

1 回答 1

1

您正在将实体映射到可嵌入对象中,这是错误的。嵌入应该只包含基本类型。简而言之,您的实体应如下所示:

@Entity
public class Question
{
    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;
    @OneToMany(mappedBy = "question")
    private Set<Answer> answers;
}

@Entity
public class Answer
{
    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;

    @ManyToOne
    private Question question;
}

@Entity
public class QuestionDisplayRule
{
    @EmbeddedId
    private QuestionDisplayRulePK key;

    @MapsId(value = "questionId")
    @ManyToOne
    @JoinColumn(name = "question_id", referencedColumnName = "id")
    private Question question;

    @MapsId(value = "answerId")
    @ManyToOne
    @JoinColumn(name = "answer_id", referencedColumnName = "id")
    private Answer answer;
}

@Embeddable
public class QuestionDisplayRulePK
{
    @Column(name = "answer_id")
    private Long answerId;
    @Column(name = "question_id")
    private Long questionId;
}
于 2012-06-07T09:18:34.840 回答