jpa-将jpql联接查询转换为条件api [英] jpa - transforming jpql join query to criteria api
问题描述
我正在尝试转换此JPQL查询;
I was trying to transform this JPQL query;
SELECT s FROM QuestionSet s JOIN s.questions q WHERE q.appointedRepetition.date < :tomorrow
与其标准api等效,这是我到目前为止所拥有的:
to its criteria api equivalent, here is what I have so far:
DateTime tomorrow = DateTime.now().plusDays(1).withTime(0,0,0,0);
CriteriaBuilder criteriaBuilder = JPA.em().getCriteriaBuilder();
CriteriaQuery<QuestionSet> query = criteriaBuilder.createQuery(QuestionSet.class);
Root<QuestionSet> root = query.from(QuestionSet.class);
Join<QuestionSet, Question> questionJoin = root.join("questions");
Predicate ownerCondition = criteriaBuilder.equal(root.get("owner"), owner);
Predicate dateCondition = criteriaBuilder.lessThan(questionJoin.<DateTime>get("appointedRepetition.date"), tomorrow);
query.where(criteriaBuilder.and(ownerCondition, dateCondition));
List<QuestionSet> result = JPA.em().createQuery(query).getResultList();
return result;
但是我得到了
play.api.Application$$anon$1: Execution exception[[IllegalArgumentException: Unable to resolve attribute [appointedRepetition.date] against path [null]]]
查看>如何转换JPQL带有与Criteria API等效的子查询?我在Criteria API部分中具有几乎相同的代码.
Looking at How to convert a JPQL with subquery to Criteria API equivalent? I have almost the same code in criteria api part.
@Entity
@SequenceGenerator(name = "wordlist_seq", sequenceName = "wordlist_seq")
public class QuestionSet {
@OneToMany(cascade = CascadeType.ALL)
private List<Question> questions;
...
}
@Entity
@SequenceGenerator(name = "question_seq", sequenceName = "question_seq")
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class Question{
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "question_seq")
private Long id;
...
}
@OneToOne(cascade = CascadeType.ALL)
private AppointedRepetition appointedRepetition;
推荐答案
您需要另一个联接,但我不能保证它会起作用,因为实体定义丢失或不完整,并且并非所有关系都按所述定义在您的评论中.无论如何,我会尝试这样做:
You need another join, but I can't assure it will work, because the entity definitions are either missing or incomplete, and not all relationships are defined as stated in your comment. Anyway, I would try this:
Join<Question, AppointedRepetition> repetition = questionJoin.join("appointedRepetition");
Predicate dateCondition = criteriaBuilder.lessThan(repetition.get("date"), tomorrow);
顺便说一句,我看到您正在使用joda的DateTime.我从未在JPA CriteriaBuilder中使用它,所以无法保证它能正常工作.
By the way, I see that you are using joda's DateTime. I have never used it with JPA CriteriaBuilder, so I can't assure it works.
这篇关于jpa-将jpql联接查询转换为条件api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!