user2101310
user2101310

Reputation: 105

Hibernate Criteria. Restrictions and max Date

I have a question about using Restrictions in Hibernate.

I have to create criteria, set some restrictions, and then choose one record with max value of Date field:

Criteria query = session.createCriteria(Storage.class)
           query.add(Restrictions.eq(USER_ID, item.getUserId()));
           query.add(Restrictions.eq(ITEM_ID, item.getItemId()));
           query.add(Restrictions.lt(PURCHASE_DATE, item.getDate()));
           query.setProjection(Projections.max(PURCHASE_DATE));
           return query.uniqueResult();

I understand that Projections will not return me a record with max Date. What approach should I choose?

Maybe I can add order to my query (ascending order on Date field) and then choose the first result?

Or could you please suggest more elegant solution?

Thank you!

Upvotes: 2

Views: 19974

Answers (1)

Philipp
Philipp

Reputation: 538

In your case you could go

A) with a DetachedQuery. E.g.,

DetachedCriteria maxQuery = DetachedCriteria.forClass( Storage.class );
maxQuery.add(Restrictions.eq(USER_ID, item.getUserId()));
maxQuery.add(Restrictions.eq(ITEM_ID, item.getItemId()));
maxQuery.add(Restrictions.lt(PURCHASE_DATE, item.getDate()));
maxQuery.setProjection( Projections.max( "PURCHASE_DATE" ) );

Criteria query = getSession().createCriteria( Storage.class );
query.add(Restrictions.eq(USER_ID, item.getUserId()));
query.add(Restrictions.eq(ITEM_ID, item.getItemId()));
query.add( Property.forName( "PURCHASE_DATE" ).eq( maxQuery ) );

Keep transactions in mind, when dealing with detached queries!

See chapter 15 of the documentation for further details on detached queries: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html

B) with HQL or SQL directly, in order to do the subselect.

See chapter 14 of the Hibernate documentation for further details on HQL: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html

Upvotes: 7

Related Questions