Francis Francis - 2 months ago 19
Java Question

ERROR: org.hibernate.hql.internal.ast.ErrorCounter - line 1:45: unexpected token : DESC on fetching the last record from the table

I am trying to fetch the last record from the database using the below hibernate query

//fetch the last data from a field in a table
Session session = _sessionFactory.getCurrentSession();
Query query = session.createQuery("select t.currentfile from file t DESC");
query.setMaxResults(1);
List<Object[]> rows = query.list();

for (Object[] row: rows) {
System.out.println(" ------------------- ");
System.out.println("current file: " + row[0]);
}


with the above hql I am getting this error:

ERROR: org.hibernate.hql.internal.ast.ErrorCounter - line 1:45: unexpected token
: DESC


what could be wrong?

Answer

Descending ('DESC' or 'desc') and Ascending ('ASC' or 'asc') can only be used with an order by clause.

So your code would have to look something like:

Query query = session.createQuery("select t.currentfile from file t 
  ORDER BY t.time_created DESC");

(time_created is only an example field as you have not added what fields you have in your table or what you are ordering by in descending order)