ORDER BY using Criteria API

后端 未结 5 1210
醉酒成梦
醉酒成梦 2020-12-24 00:23

When I write a HQL query

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

Eve

相关标签:
5条回答
  • 2020-12-24 00:39

    It's hard to know for sure without seeing the mappings (see @Juha's comment), but I think you want something like the following:

    Criteria c = session.createCriteria(Cat.class);
    Criteria c2 = c.createCriteria("mother");
    Criteria c3 = c2.createCriteria("kind");
    c3.addOrder(Order.asc("value"));
    return c.list();
    
    0 讨论(0)
  • 2020-12-24 00:56

    You can add join type as well:

    Criteria c2 = c.createCriteria("mother", "mother", CriteriaSpecification.LEFT_JOIN);
    Criteria c3 = c2.createCriteria("kind", "kind", CriteriaSpecification.LEFT_JOIN);
    
    0 讨论(0)
  • 2020-12-24 00:57

    For Hibernate 5.2 and above, use CriteriaBuilder as follows

    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();
    
    0 讨论(0)
  • 2020-12-24 00:58

    This is what you have to do since sess.createCriteria is deprecated:

    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();
    
    0 讨论(0)
  • 2020-12-24 01:02

    You need to create an alias for the mother.kind. You do this like so.

    Criteria c = session.createCriteria(Cat.class);
    c.createAlias("mother.kind", "motherKind");
    c.addOrder(Order.asc("motherKind.value"));
    return c.list();
    
    0 讨论(0)
提交回复
热议问题