看起来 API 不直接支持您想要的,但您可能会考虑一些解决方法。
解决方案1:
DetachedCriteria criteria = DetachedCriteria.forClass(Contract.class)
.add(Restrictions.le("startDate", toEndOfYear(year))
.add(Restrictions.ge("endDate", toStartOfYear(year)));
public Date toStartOfYear(int year) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.DAY_OF_YEAR, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
return calendar.getTime();
}
public Date toEndOfYear(int year) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.DAY_OF_YEAR, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND,-1);
return calendar.getTime();
}
两种方法的示例输出:
System.out.println(toStartOfYear(2013));
System.out.println(toEndOfYear(2013));
Mon Dec 31 00:00:00 MYT 2012
Sun Dec 30 23:59:59 MYT 2012
解决方案2:
DetachedCriteria criteria = DetachedCriteria.forClass(Contract.class)
.add(Restrictions.sqlRestriction("YEAR(startDate) >= ? ", year,Hibernate.INTEGER))
.add(Restrictions.sqlRestriction("YEAR(endDate) <= ? ", year,Hibernate.INTEGER));