ORDER BY使用Criteria API

时间:2009-11-22 21:55:13

标签: java hibernate sql-order-by hql

当我编写HQL查询时

Query q = session.createQuery("SELECT cat from Cat as cat ORDER BY cat.mother.kind.value");
return q.list();

一切都很好。但是,当我写一个Criteria

Criteria c = session.createCriteria(Cat.class);
c.addOrder(Order.asc("mother.kind.value"));
return c.list();

我收到例外org.hibernate.QueryException: could not resolve property: kind.value of: my.sample.data.entities.Cat

如果我想使用Criteria and Order,我该如何表达我的“order by”?

5 个答案:

答案 0 :(得分:104)

您需要为mother.kind创建别名。你是这样做的。

Criteria c = session.createCriteria(Cat.class);
c.createAlias("mother.kind", "motherKind");
c.addOrder(Order.asc("motherKind.value"));
return c.list();

答案 1 :(得分:8)

如果没有看到映射,很难确定(请参阅@ Juha的评论),但我认为您需要以下内容:

Criteria c = session.createCriteria(Cat.class);
Criteria c2 = c.createCriteria("mother");
Criteria c3 = c2.createCriteria("kind");
c3.addOrder(Order.asc("value"));
return c.list();

答案 2 :(得分:5)

您也可以添加联接类型:

Criteria c2 = c.createCriteria("mother", "mother", CriteriaSpecification.LEFT_JOIN);
Criteria c3 = c2.createCriteria("kind", "kind", CriteriaSpecification.LEFT_JOIN);

答案 3 :(得分:5)

这是你不得不做的事情,因为不推荐使用sess.createCriteria:

CriteriaBuilder builder = getSession().getCriteriaBuilder();
CriteriaQuery<User> q = builder.createQuery(User.class);
Root<User> usr = q.from(User.class);
ParameterExpression<String> p = builder.parameter(String.class);
q.select(usr).where(builder.like(usr.get("name"),p))
  .orderBy(builder.asc(usr.get("name")));
TypedQuery<User> query = getSession().createQuery(q);
query.setParameter(p, "%" + Main.filterName + "%");
List<User> list = query.getResultList();

答案 4 :(得分:0)

对于Hibernate 5.2及更高版本,请使用CriteriaBuilder,如下所示

CriteriaBuilder builder = sessionFactory.getCriteriaBuilder();
CriteriaQuery<Cat> query = builder.createQuery(Cat.class);
Root<Cat> rootCat = query.from(Cat.class);
Join<Cat,Mother> joinMother = rootCat.join("mother");  // <-attribute name
Join<Mother,Kind> joinMotherKind = joinMother.join("kind");
query.select(rootCat).orderBy(builder.asc(joinMotherKind.get("value")));
Query<Cat> q = sessionFactory.getCurrentSession().createQuery(query);
List<Cat> cats = q.getResultList();