我正在开发一个问答式 Web 应用程序,其中两个实体是问答。一个问题有很多答案。此外,一个答案有很多答案(我将其称为答案的子答案):
@Entity
@Table(name = "questions")
public class Question implements Serializable {
@Id
private Long id;
@OneToMany(mappedBy = "question")
private Set<Answer> answers;
//...
}
@Entity
@Table(name = "answers")
public class Answer implements Serializable {
@Id
private Long id;
@ManyToOne
private Question question;
@ManyToOne
private Answer parentAnswer;
@OneToMany(mappedBy = "parentAnswer")
private Set<Answer> childAnswers;
//...
}
在获取特定答案的子答案时,Hibernate 使用类似于以下内容的查询:
select ... from answers childanswe0_ where childanswe0_.parent_answer_id=?
我想做的是自定义 WHERE 子句,以便也包含问题 ID;我想要这样的东西:
select ... from answers childanswe0_ where
childanswe0_.question_id=? and childanswe0_.parent_answer_id=?
原因是我有一个关于我想使用的答案(question_id,parent_answer_id)的索引。我目前没有,也不想在 answers(parent_answer_id) 上添加索引,因此当前查询会导致全表扫描。
我尝试@JoinColumns
在该childAnswers
字段上使用,但这导致错误:org.hibernate.AnnotationException:标记为 mappedBy 的关联不得定义 @JoinTable 或 @JoinColumn 之类的数据库映射:test.domain.Answer.childAnswers
我也尝试@JoinColumns
在该parentAnswer
字段上使用,但这导致错误:org.hibernate.AnnotationException:引用 test.domain.Answer 的外键来自 test.domain.Answer 的列数错误。应该是 1
我的 JPA 提供程序是 Hibernate 5.2.17。
如何确保用于选择父答案的子答案的查询的 WHERE 子句包含父答案的问题 ID?