Java 使用LIMIT和MySQL按订单

Java 使用LIMIT和MySQL按订单,java,mysql,sql,jpql,Java,Mysql,Sql,Jpql,我在MySQL查询中遇到问题,其中一行的限制为1。但当与order by一起使用时,它不起作用 mysql工作台中的查询如下所示: select * from train t where t.togId = 1125 and t.tilDato >= '2013-12-20' order by t.fraDato LIMIT 1; 然而,当我通过javacode运行此命令时,在我的服务器上,我得到了这个stacktrace: Exception Description: Syn

我在MySQL查询中遇到问题,其中一行的限制为1。但当与order by一起使用时,它不起作用

mysql工作台中的查询如下所示:

select * from train t 
where t.togId = 1125 
and t.tilDato >= '2013-12-20' 
order by t.fraDato LIMIT 1; 
然而,当我通过javacode运行此命令时,在我的服务器上,我得到了这个stacktrace:

Exception Description: 
Syntax error parsing [select t from train t where t.togId = :togId 
and t.tilDato >= :todaysdate order by t.fraDato LIMIT 1].

[102, 103] The ORDER BY clause has 't.fraDato ' and 'LIMIT ' 
that are not separated by a comma.

[108, 109] The ORDER BY clause has 'LIMIT ' and '1' that are not separated by a comma.
查询的创建方式如下:

Query query = em.createQuery("select t from train t where t.togId = :togId" +
    " and t.tilDato >= :todaysdate order by t.fraDato LIMIT 1")
    .setParameter("togId", togId)
    .setParameter("todaysdate", new Date());

使用
query.setMaxResults()
代替
Limit
将不适用于
hql

Query q = session.createQuery("FROM table");
q.setFirstResult(start);
q.setMaxResults(maxRows);
请参阅hibernate论坛中发布的以下链接


您似乎在使用JPQL,即Java持久性查询语言。MySQL和JPQL(或Hibernate)是完全不同的查询语言,它们都有自己的特定语法。LIMIT构造仅在MySQL中可用,它不是任何SQL标准的一部分。JPA中的功能是通过在
query
对象上设置最大结果数来模拟的

因此,您应该使用

query.setMaxResults(1);

select t
替换为
select*
也可以执行
select t.*
。在工作台查询中,您可以选择*。您的java代码已选择t。除非您的训练表有一个名为t的列,否则您将得到某种错误。