76

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

Everything is fine. However, when I write a Criteria

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

I get an exception org.hibernate.QueryException: could not resolve property: kind.value of: my.sample.data.entities.Cat

If I want to use Criteria and Order, how should I express my "order by"?

1
  • 1
    What does your Cat class and its mapping look like? Commented Nov 22, 2009 at 21:57

5 Answers 5

109

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(); 
Sign up to request clarification or add additional context in comments.

2 Comments

session.createCriteria is deprecated
I'm using Hibernate 5.0.7 and session.createCriteria is not deprecated.
9

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

1 Comment

Find this appropriate for Hibernate 5.2.
8

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

Comments

5

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

Comments

3

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.