简体   繁体   中英

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!

In your case you could go

A) with a DetachedQuery. Eg,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM