Reputation: 6537
Suppose I have a class TransactionDetails. This table holds transaction of last 10 year. Now How can i get all TransactionDetails of current year
I am using criteria as following
Criteria criteria = session.getCurrentSession().createCriteria(TransactionDetails.class);
criteria.add(Restrictions.eq("entryDate", thisYear));
return (List<TransactionDetails>) criteria.list();
I know I can achieve this by detecting beginning of year and end of year and the do a query with between operator. But I am looking for a way do this in one line. e.g. like in sql we use CURDATE()
How can this be done??
Upvotes: 1
Views: 905
Reputation: 27986
Try Restrictions.between("entryDate", loDate, highDate)
Edit:
You could also probably use a (vendor specific) sql restriction.
eg: Restrictions.sqlRestriction("to_char(entry_date, 'YYYY') = ?", "2015", StringType.INSTANCE)
Note: This will likely perform worse than between
Upvotes: 1
Reputation: 1928
You need to use between
restriction together with date range:
Calendar lowCal = Calendar.getInstance();
lowCal.set(Calendar.DAY_OF_YEAR, lowCal.getActualMinimum(Calendar.DAY_OF_YEAR);
Date lowDate = lowCal.getTime();
Calendar highCal = Calendar.getInstance();
lowCal.set(Calendar.DAY_OF_YEAR, lowCal.getActualMaximum(Calendar.DAY_OF_YEAR);
Date highDate = highCal.getTime();
Criteria criteria = session.getCurrentSession().createCriteria(TransactionDetails.class);
criteria.add(Restrictions.between("entryDate", lowDate, highDate));
return (List<TransactionDetails>) criteria.list();
Dates are obtained by basic Java Calendar
API. If is of course possible to obtain dates in different ways, for example using Joda Time.
Upvotes: 1