0

I will like to select top 10 records based on the SQL statement below using CriteriaBuilder from JPA.

SELECT * from RECORDTABLE rt
where rt.LASTUPDATED > startDate
and rt.LASTUPDATE < endDate
order by rt.TOTALNUMBER asc;

So far I used Predicates for the between Dates.

sina72
  • 4,931
  • 3
  • 35
  • 36
jonleech
  • 461
  • 1
  • 6
  • 30

1 Answers1

5

I found the answer after more searching online, I don't want to answer my own question caused I will look like a douche but the forum doesn't allow me to remove this question when there are answers(though not to my question)

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Record> query = cb.createQuery(Record.class);
Root sm = query.from(Record.class);

List<Predicate> predicateList = new ArrayList();

predicateList.add(cb.greaterThanOrEqualTo(sm.get(COL_TIMESTAMP), startDate));
predicateList.add(cb.lessThanOrEqualTo(sm.get(COL_TIMESTAMP), endDate));

if (predicateList.size() > 0)
{
    query.where(predicateList.toArray(new Predicate[predicateList.size()]));
}
**query.orderBy(cb.desc(sm.get(COL_TOTALRECORD)));**
List<Record> tempList = em.createQuery(query)
            .setFirstResult(0)
            .setMaxResults(10)
            .getResultList();

This is what I was looking for

query.orderBy(cb.desc(sm.get(COL_TOTALRECORD)));
jonleech
  • 461
  • 1
  • 6
  • 30
  • 1
    There is nothing wrong with answering your own question (search MetaSO for discussions). You should mark this as the accepted solution. – Tilo Sep 17 '14 at 18:10