我有一个实体Answer,它有一个复合id AnswerId,它有一个Person实体和一个Question实体,它们分别有personId和questionId的字符串ID。此外,Question实体有一个字段questionText。
如果我尝试这样的话:
Criteria criteria = session.createCriteria(AnswerEntity.class);
criteria.add(Restrictions.eq("answerId.person.personId", personId));
criteria.add(Restrictions.eq("answerId.question.questionId", questionId));
它的工作原理是它根据提供的personId和questionId过滤结果。
但是,如果我尝试:
Criteria criteria = session.createCriteria(AnswerEntity.class);
criteria.add(Restrictions.eq("answerId.person.personId", personId));
criteria.add(Restrictions.like("answerId.question.questionText",questionText));
失败了。它说它无法找到questionText,生成的SQL显示原因:
SELECT this_.PERSON_ID AS PERSON6_5_0_,
this_.QUESTION_ID AS QUESTION5_5_0_,
this_.THEIR_ANSWER AS THEIR3_5_0_,
FROM ANSWER this_
WHERE q1_.QUESTION_TEXT LIKE ?
AND this_.PERSON_ID=?
如何在答案和问题之间加入,以便我可以访问questionText?我尝试添加像
这样的别名criteria.createAlias("answerId.question", "q");
criteria.add(Restrictions.like("q.questionText", "%" + text + "%"));
但这似乎不起作用。任何人都能提供一些帮助,说明我做错了吗?
编辑:奇怪的是,Person实体也有一组Answers,这样我就可以对Person进行查询并使用类似"answers.answerId.question.questionText"
的限制进行过滤,它实际上有效。我不确定有什么不同。
编辑:我的实体(没有getter / setters / equals / etc)
@Entity
@Table(name = "ANSWER")
public class AnswerEntity implements Serializable
{
private static final long serialVersionUID = -8254277382097937813L;
@EmbeddedId
private AnswerId answerId;
@Column(name = "THEIR_ANSWER")
private int theirAnswer;
}
@Embeddable
public class AnswerId implements Serializable
{
private static final long serialVersionUID = 7025913625856563058L;
@OneToOne
@Index(name = "ANSWER_QUESTION_ID_INDEX")
@JoinColumn(name = "QUESTION_ID")
@ForeignKey(name = "FKA1_QUESTION_ID")
private QuestionEntity question;
@ManyToOne
@Cascade(CascadeType.ALL)
@Index(name = "ANSWER_PERSON_ID_INDEX")
@JoinColumn(name = "PERSON_ID")
@ForeignKey(name = "FKA2_PERSON_ID")
private PersonEntity person;
}
@Entity
@Table(name = "QUESTION")
public class QuestionEntity implements Serializable
{
private static final long serialVersionUID = -3083000088157555984L;
@Id
@Column(name = "QUESTION_ID", nullable = false)
private String questionId;
@Index(name = "QUESTION_TEXT_INDEX")
@Column(name = "QUESTION_TEXT", length = 4000, nullable = false)
private String questionText;
}
答案 0 :(得分:1)
只是猜测,试试:
criteria.createAlias("question.questionText", "qText");
criteria.add(Restrictions.like("answerId.qText", "%" + text + "%"));
编辑:这背后的推理(为了猜测一个有根据的猜测;)是您不需要别名或SubCriteria
导航到myEembedded.myProperty
等嵌入属性。您需要别名或SubCriteria
才能导航到相关实体的属性,例如myRelatedEntity.myProperty
。