如何使用Hibernate从MySQL获得最后一个记录?(How to get last recor

2019-08-01 22:06发布

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

并在日志中我得到:

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

什么happend“从LAHETYS”? 什么是处理与HQL和/或与SQL的最佳做法?

另一个问题:

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

我得到一个例外:

Ljava.lang.Object; cannot be cast to Lahetys 

所以我不能投的目的是我Lahetys对象,怪异?

谢谢! 萨米

Answer 1:

你的HQL查询无效。 限制是不是一个有效的HQL子句。 要做到这一点在Hibernate中,只是做

Query query = session.createQuery("from lahetys order by lahetysNro DESC");
query.setMaxResults(1);
Lahetys last = (Lahetys) query.uniqueResult();


Answer 2:

当你使用HQL,应指定完全合格的类名,而不是表名。 用同样的方法,你应该指定propertyName的,而不是列名。 也请记住,无论是案例 - 敏感。

看着你的查询和你得到的例外,我假设lahetys是你的表名和lahetysNro是你的列名。

你应该例如使用:如果您Lahetys类位于com文件夹:

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

对于你的第二个问题:

在这里,你已经使用SQL,而不是HQL。 当你以这种方式使用SQL与Hibernate,它总是返回List<Object[]>不是List<Lahetys[]>



文章来源: How to get last record from Mysql using Hibernate?