使用Criteria API进行订购


73

当我编写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();

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

如果我想使用“标准和顺序”,我应该如何表达我的“顺序”?


1
您的Cat类及其映射是什么样的?
JuhaSyrjälä09年

Answers:


108

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

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

session.createCriteria已弃用
Stepan Yakovenko

我正在使用Hibernate 5.0.7,session.createCriteria并且不推荐使用。
卡梅洛格'18

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();

6

由于不推荐使用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();

找到适合的Hibernate 5.2
Cryptor


1

对于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();
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.