Question

I have a pseudo sql query which looks like this:

from TableA as a 
      join fetch TableB as b
 WHERE 
    (a.id, a.revision) IN (  SELECT id, MAX (revision) FROM TableA GROUP BY id)
     and 
    (b.id, b.revision) IN (  SELECT id, MAX (revision) FROM TableB GROUP BY id);

and I would like to use the hibernate criteria api to do the same.

I have a solution but it has a weakness:

final Criteria criteria = getSession().createCriteria(TableA.class, "a");
criteria.setFetchMode("btables", FetchMode.JOIN); //$NON-NLS-1$
criteria.add(Restrictions.sqlRestriction("({alias}.id, {alias}.revision) IN (  SELECT id, MAX (revision) FROM TableA GROUP BY id)"));

Criteria bSubCriteria = criteria.createCriteria("a.btables", "b");
bSubCriteria.add(Restrictions.sqlRestriction("({alias}.id, {alias}.revision) IN (  SELECT id, MAX (revision) FROM TableB GROUP BY id)"));

My problem with the solution is that I have to explicitly name the table in the sql restriction.

Does anyone have a better way I could model this, without injecting any sql, or by getting Hibernate to resolve the name of the table?

Was it helpful?

Solution

There's not an out of the box way to do this because sqlRestriction only interprets the expression {alias} but there is no expression to get the tablename for the alias. However, you could look up the table name from Hibernate/Entity metadata and then plug that into your sqlRestriction (using some less undesirable string concatenation).

You'd want to create your own utility class to get tablename from the entity class using one of the methods described here: Get the table name from the model in Hibernate

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top