【问题标题】:ORDER BY using Criteria APIORDER BY 使用 Criteria API
【发布时间】:2010-12-19 07:17:46
【问题描述】:

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

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

【问题讨论】:

  • 您的 Cat 类及其映射是什么样的?

标签: java hibernate sql-order-by hql


【解决方案1】:

如果没有看到映射很难确定(参见@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】:

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

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

    【讨论】:

    • session.createCriteria 已弃用
    • 我使用的是 Hibernate 5.0.7 并且 session.createCriteria 未被弃用。
    【解决方案3】:

    您也可以添加连接类型:

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

    【讨论】:

      【解决方案4】:

      这是你必须做的,因为 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的。
      【解决方案5】:

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

      【讨论】:

        猜你喜欢
        • 2016-03-09
        • 1970-01-01
        • 2013-04-30
        • 2013-11-11
        • 1970-01-01
        • 2013-11-02
        • 2016-10-31
        • 1970-01-01
        • 2020-11-14
        相关资源
        最近更新 更多