我在CRITERIA API中有一个查询,如下所示:
CriteriaQuery<Application> query = builder.get().createQuery(Application.class).distinct(true);
Root<Application> root = query.from(Application.class);
root.join(Application_.answerSets).get(AnswerSet_.createDate);
我想获取记录,其中createDate
超过5天。我不知道如何实现这一目标。我对CRITERIA API非常不满意,但我正在研究的项目是使用它,所以到目前为止我遇到了麻烦。
答案 0 :(得分:3)
以下代码是@Rembo建议的说明。请注意,关键是使用方法“.where(...)”
public List<Application> getOlderThanNDays( int days )
{
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Application> cq = cb.createQuery( Application.class );
Root<Application> root = cq.from( Application.class );
long today = System.currentTimeMillis();
long nDays = days * 24 * 60 * 60 * 1000;
long nDaysAgo = today - nDays;
Date nDaysAgoDate = new Date( nDaysAgo );
// Is here the response to your question?
cq.where( cb.lessThanOrEqualTo( root.get(Application_.date), nDaysAgoDate ) );
TypedQuery<Application> q = entityManager.createQuery( cq );
List<Application> list = q.getResultList();
return list;
}
我假设你在类Application_.java中使用了@StaticMetamodel注释,并且日期的类型是java.sql.Date。