我正在尝试映射3个实体:Question、Answer和QuestionDisplayRule。问题有许多答案和许多问题显示规则,每个规则都属于一个问题。QuestionDisplayRule有一个Question、一个Answer和一个String值字段。QuestionDisplayRule的数据库表如下所示:
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;
}
问题是,如果我在DB中手动添加记录,但不保存它们,那么它加载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);
有什么想法吗?谢谢
您正在将实体映射到可嵌入对象中,这是错误的。可嵌入的应该只包含基类型。简而言之,你的实体应该是这样的:
@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;
}