ORDER BY使用Criteria API

当我写一个HQL查询

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

一切安好。 但是,当我写一个标准

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

我得到一个exceptionorg.hibernate.QueryException: could not resolve property: kind.value of: my.sample.data.entities.Cat

如果我想使用标准和秩序,我应该如何expression我的“秩序”?

您需要为mother.kind创build一个别名。 你这样做。

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

很难确定没有看到映射(参见@ 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(); 

您也可以添加连接types:

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

这是你必须做的,因为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();