Search code examples
javamysqlsqljpql

ORDER BY with LIMIT and MySQL


I am having issues with a MySQL query, where I am getting one row with a LIMIT 1. But when using this together with order by it does not work.

The query that is working in the mysql workbench is as follows:

select * from train t 
where t.togId = 1125 
and t.tilDato >= '2013-12-20' 
order by t.fraDato LIMIT 1; 

However, when I am running this through javacode and on my server im getting this 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.

The query is created like this:

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());

Solution

  • You seem to be using JPQL, that is Java Persistence Query Language. MySQL and JPQL (or Hibernate) are completely different query languages and each of them has their own specific syntax. The LIMIT construct is available only in MySQL and it is not part of any SQL standard. The functionality in JPA is simulated by setting maximum number of results on the query object.

    So instead of LIMIT 1 you should use

    query.setMaxResults(1);