What is the LIMIT clause alternative in JPQL?

前端 未结 7 680
不思量自难忘°
不思量自难忘° 2020-12-13 03:26

I\'m working with PostgreSQL query implementing in JPQL.

This is a sample native psql query which works fine,

SELECT * FROM students ORDER BY id DESC         


        
7条回答
  •  情歌与酒
    2020-12-13 04:15

    As stated in the comments, JPQL does not support the LIMIT keyword.

    You can achieve that using the setMaxResults but if what you want is just a single item, then use the getSingleResult - it throws an exception if no item is found.

    So, your query would be something like:

    TypedQuery query = entityManager.createQuery("SELECT s FROM Students s ORDER BY s.id DESC", Student.class);    
    query.setMaxResults(1);
    

    If you want to set a specific start offset, use query.setFirstResult(initPosition); too

提交回复
热议问题