简体   繁体   English

如何使用Hibernate从Mysql获取最后一条记录?

[英]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"? “LAHETYS”发生了什么? What is the best practice to handle that with HQL or/and with SQL? 使用HQL或/和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? 所以我不能把一个物体投射到我的Lahetys物体上,很奇怪?

Thank you! 谢谢! Sami 萨米

Your HQL query is invalid. 您的HQL查询无效。 LIMIT is not a valid HQL clause. LIMIT不是有效的HQL子句。 To do that in Hibernate, just do 要在Hibernate中做到这一点,就这样做

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

When you're using HQL, you should specify fully qualified className instead of tableName. 在使用HQL时,应指定完全限定的className而不是tableName。 The same way you should specify propertyName instead of columnName. 您应该使用相同的方式指定propertyName而不是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. 看看你的查询和你得到的例外情况,我假设lahetys是你的表名和lahetysNro是你的列名。

You should use for example: If your Lahetys class is located at com folder: 您应该使用例如:如果您的Lahetys类位于com文件夹:

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. 在这里,您使用的是SQL而不是HQL。 When you use SQL with hibernate in such a way, it always returns List<Object[]> & not List<Lahetys[]> . 当你以这种方式使用SQL和hibernate时,它总是返回List<Object[]>而不是List<Lahetys[]>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM