I have been struggling with this for a while, so I am hoping that someone may be able to give me some guidance. I have two tables:
WardTransactions:
+-----------+
| Field |
+-----------+
| Id |
| VisitId |
| Event |
| EventTime |
+-----------+
Visits:
+---------------+
| Field |
+---------------+
| Id |
| VisitNumber |
+---------------+
There can be many WardTransactions for each visit. I am trying to use Hibernate Criteria/Projections to find the most recent WardTransaction for a specific visit. For example:
public WardTransaction findLast(Visit visit) {
DetachedCriteria maxQuery = DetachedCriteria.forClass( WardTransaction.class );
maxQuery.setProjection( Projections.max( "id" ) );
Criteria query = getSession().createCriteria( WardTransaction.class )
.createAlias("visit", "visit")
.add(Restrictions.eq("visit.id", visit.getId()))
.add(Property.forName( "id" ).eq( maxQuery ));
return (WardTransaction) query.uniqueResult();
}
This is not working. From looking at the resulting query, it appears that it is doing an inner join with the Max WardTransaction.Id rather than the Maximum for the records with the required Visit. That is (modified to make it clearer):
select
a.Id,
a.VisitId,
a.Event,
a.EventTime,
b.Id,
b.VisitNumber,
from
WardTransactions a
inner join
Visits b
on a.VisitId=b.Id
where
b.Id='22'
and a.Id = (
select
max(a.Id) as y0_
from
WardTransactions a
)
I have tried other approaches, but none result in the solution I am looking for.
Any advice, guidance appreciated.
You can of course do the same with Criteria, but HQL is much more readable, IMHO.