小编典典

如何使用Hibernate从Mysql获取最新记录?

hibernate

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

“来自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对象上,很奇怪吗?

谢谢!佐美


阅读 266

收藏
2020-06-20

共1个答案

小编典典

您的HQL查询无效。LIMIT不是有效的HQL子句。要在Hibernate中做到这一点,只需

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