如何使用 Hibernate 从 Mysql 获取最后一条记录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13069689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get last record from Mysql using Hibernate?
提问by Sami
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?
“来自LAHETYS”发生了什么?使用 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
谢谢!萨米人
回答by JB Nizet
Your HQL query is invalid. LIMIT is not a valid HQL clause. To do that in Hibernate, just do
您的 HQL 查询无效。LIMIT 不是有效的 HQL 子句。要在 Hibernate 中执行此操作,只需执行
Query query = session.createQuery("from lahetys order by lahetysNro DESC");
query.setMaxResults(1);
Lahetys last = (Lahetys) query.uniqueResult();
回答by RAS
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.
当您使用 HQL 时,您应该指定完全限定的 className 而不是 tableName。与您应该指定 propertyName 而不是 columnName 的方式相同。还要记住,两者都是区分大小写的。
Looking at your queries & the exception you're getting, I'm assuming that lahetysis your table name & lahetysNrois your column name.
查看您的查询和您收到的异常,我假设lahetys是您的表名,而lahetysNro是您的列名。
You should use for example: If your Lahetysclass 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.
When you use SQL with hibernate in such a way, it always returns List<Object[]>
& not List<Lahetys[]>
.
在这里,您使用了 SQL 而不是 HQL。当您以这种方式将 SQL 与 hibernate 结合使用时,它总是返回List<Object[]>
& not List<Lahetys[]>
。