Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last record from Mysql using Hibernate?

List<Lahetys> last = session.createQuery("from lahetys order by lahetysNro DESC LIMIT 1").list();

and in the log I got:

INFO: Hibernate: select  from order by  lahetysNro DESC LIMIT 1
WARN: SQL Error: 1064, SQLState: 42000
ERROR: 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 order by  lahetysNro DESC LIMIT 1' at line 1

What has happend to "from LAHETYS"? What is the best practice to handle that with HQL or/and with SQL?

Another problem:

Lahetys last = (Lahetys)session.createSQLQuery("select * from lahetys order by lahetysNro DESC LIMIT 1").uniqueResult();
session.getTransaction().commit();  

and I get a exception:

Ljava.lang.Object; cannot be cast to Lahetys 

So I can't cast an object to my Lahetys-object, weird?

Thank you! Sami

like image 443
Sami Avatar asked Oct 25 '12 13:10

Sami


People also ask

How can I get the last record of a table?

We can use the command FIRST() to extract the first entry of a particular column and LAST() to extract the last entry of a particular column in a Table.

What is the query to fetch last record?

To get the last record, the following is the query. mysql> select *from getLastRecord ORDER BY id DESC LIMIT 1; The following is the output. The above output shows that we have fetched the last record, with Id 4 and Name Carol.

Which method is used to display a last record from the database?

The LAST() function in Structured Query Language shows the last value from the specified column of the table.


2 Answers

Your HQL query is invalid. LIMIT is not a valid HQL clause. To do that in Hibernate, just do

Query query = session.createQuery("from lahetys order by lahetysNro DESC");
query.setMaxResults(1);
Lahetys last = (Lahetys) query.uniqueResult();
like image 75
JB Nizet Avatar answered Sep 30 '22 01:09

JB Nizet


When you're using HQL, you should specify fully qualified className instead of tableName. The same way you should specify propertyName instead of columnName. Also keep in mind that both are case - sensitive.

Looking at your queries & the exception you're getting, I'm assuming that lahetys is your table name & lahetysNro is your column name.

You should use for example: If your Lahetys class is located at com folder:

List<Lahetys> last = session.createQuery("from com.Lahetys order by lahetysNro DESC LIMIT 1").list();

For your 2nd question:

Here you have used SQL instead of HQL. When you use SQL with hibernate in such a way, it always returns List<Object[]> & not List<Lahetys[]>.

like image 25
RAS Avatar answered Sep 30 '22 03:09

RAS