Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Selecting the last record in the table using Hibernate

 
Baranidharan Ramakoti
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone please tell me with an example, how to retrieve the last row in the table. I am using MySQL and Hibernate

I have tried with max(rowid), order by desc limit 1. But it doesn't work. I am getting an error,"could not execute Query" You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from' at line 1"

The code is:
String sqlquery="select MAX(rplogid) from rplogtable";
Query query = session1.createQuery(sqlquery);
List lst=query.list();
Integer x=(Integer)lst.get(0);
System.out.println("Value of max(rplogid)="+lst.get(0));
data=(RPLog)session1.get(pkg1.RPLog.class, x);

Please help me. I am struggling with this one for more than a day.
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Define a primary key, make it numeric and order your records accordingly in your select statement. This will give you the last inserted row - since this will have the highest primary key. Don't use last row logic; this will only work on databases that support concept of row order. This is a concept of very debatable merit given that primary keys identify rows anyway so why use a rowid?
 
Baranidharan Ramakoti
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

In my table, rplogid is a primary key, which is auto-incremented and is of type int. In that case, the query, select Max(rplogid) should return me the last row in the database. I am not using the last row logic.

I also tried arranging the table in descending order using the above mentioned primary key and then getting the first row using "limit 1" clause. I still get the same error.

Please help me out. It is the second day for me trying to solve this issue. Seems to be simple. But its killing my time and eating out my head.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic