如何使用JPA Criteria查询编写此查询?

时间:2012-03-29 13:28:52

标签: java jpa-2.0

任何人都可以帮助我获取下面提到的JPA查询的JPA条件查询。

SELECT p,l FROM Person p 
LEFT JOIN Language l ON (p.language = l.language and l.locale like :locale) 
AND p.name like :name 
AND p.time BETWEEN :startDate 
AND :endDate order by name asc

2 个答案:

答案 0 :(得分:12)

假设Person与语言有关系,那就是你在旧的Hibernate中会做的事情:

Criteria criteria = entityManager.createCriteria(Person.class);
Criteria languageCriteria = criteria.createCriteria("language");

languageCriteria.add(Restrictions.like("locale", locale));

criteria.add(Restrictions.like("name", name));
criteria.add(Restrictions.between("time", startDate, endDate));

criteria.addOrder(Order.asc("name"));

我第一次尝试JPA 2.0:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Person> criteria = builder.createCriteria(Person.class);
Root<Person> pRoot = criteria.from(Person.class);
Join<Person, Language> langJoin = criteria.join("language", JoinType.LEFT);

Predicate conjunction = builder.conjunction();

criteria.where(builder.and(
    builder.like(langJoin.get(Language_.locale), locale),
    builder.like(pRoot.get(Person_.name), name),
    builder.between(pRoot.get(Person_.time), startDate, endDate));

criteria.orderBy(builder.asc(pRoot.get(Person_.name)));

如果适合您,请告诉我。

编辑:更新了查询,只能使用一次where来电。

答案 1 :(得分:7)

尽管johncarl给出的答案被接受,但对我来说看起来并不正确。 CriteriaQuery.where()的JavaDocs说:

  

根据修改查询以限制查询结果   指定的布尔表达式。替换之前添加的   限制(如果有的话)。

据我了解,以下每一行(给出限制)都将覆盖先前给出的限制:

criteria.where(builder.like(langJoin.get(Language_.locale), locale));
criteria.where(builder.like(pRoot.get(Person_.name), name));
criteria.where(builder.between(pRoot.get(Person_.time), startDate, endDate));

这意味着最终只保留最后一个限制(开始和结束日期之间)。

我建议对johncarl的答案进行以下修改:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Person> criteria = builder.createCriteria(Person.class);
Root<Person> pRoot = criteria.from(Person.class);
Join<Person, Language> langJoin = criteria.join("language", JoinType.LEFT);

Predicate[] restrictions = new Predicate[] { 
    builder.like(langJoin.get(Language_.locale), locale),
    builder.like(pRoot.get(Person_.name), name),
    builder.between(pRoot.get(Person_.time), startDate, endDate)
};

criteria.where(builder.and(restrictions));

criteria.orderBy(builder.asc(pRoot.get(Person_.name)));

然而,这段代码看起来真的很难看!如果您错了,请随时编辑,如果您看到更好的解决方案,请发表评论!我会优雅的!