View Full Version : Hibernate HQL - retrieve with most recent date field?
davout
Apr 10th, 2007, 08:39 AM
I want to retrieve a record from an invoice table that includes the most recent invoice date.
In SQL this would be something like...
select * from Invoice where InvoiceDate = (select Max(InvoiceDate) from Invoice)
How would this be constructed in HQL?
karldmoore
Apr 10th, 2007, 01:06 PM
It's always a good idea to have a read of the reference manual.
http://www.hibernate.org/hib_docs/v3/reference/en/html_single/#queryhql-aggregation
Andrei Stefan
Apr 11th, 2007, 07:12 AM
And also this section: http://www.hibernate.org/hib_docs/v3/reference/en/html_single/#queryhql-subqueries
cobra82
Apr 11th, 2007, 08:24 AM
you can use Hibernate Criteria like
Criteria criteria = getSession().createCriteria(Invoice.class).setProj ection(Projections.max("InvoiceDate"));
karldmoore
Apr 11th, 2007, 11:34 AM
Or if you really, really want to. You can even do it in native SQL through Hibernate. I think that's most of the options.
http://www.hibernate.org/hib_docs/v3/reference/en/html_single/#querysql
objec
Apr 20th, 2007, 06:14 PM
you can use Hibernate Criteria like
Criteria criteria = getSession().createCriteria(Invoice.class).setProj ection(Projections.max("InvoiceDate"));
Actually this Criteria query will only generate the subquery portion: select Max(InvoiceDate) from Invoice
To get the full query you could use this:
DetachedCriteria maxQuery = DetachedCriteria.forClass( Invoice.class );
maxQuery.setProjection( Projections.max( "InvoiceDate" ) );
Criteria query = getSession().createCriteria( Invoice.class );
query.add( Property.forName( "InvoiceDate" ).eq( maxQuery ) );
vBulletin® v3.8.4, Copyright ©2000-2010, Jelsoft Enterprises Ltd.