JPQL不允许在由HQL生成的查询中添加limit关键字。您会收到以下异常。
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token:
LIMIT near line 1
但是不用担心,有一种替代方法可以在由HQL生成的查询中使用limit关键字,只需按照以下步骤操作。
Sort.by(sortBy).descending() // 按降序获取记录
pageSize = 1 // 从降序结果集中获取第一条记录。
请参考以下服务类
服务:
@Autowired
StudentRepository repository;
public List<Student> getLastStudentDetails(Integer pageNo, Integer pageSize, String sortBy)
{
Integer pageNo = 0;
Integer pageSize = 1;
String sortBy = "id";
Pageable paging = PageRequest.of(pageNo, pageSize, Sort.by(sortBy).descending());
Slice<Student> pagedResult = repository.findLastStudent(paging);
return pagedResult.getContent();
}
你的仓库接口应该实现 PagingAndSortingRepository
仓库:
public interface StudentRepository extends JpaRepository<Student,Long>, PagingAndSortingRepository<Student,Long>{
@Query("select student from Student student")
Slice<Student> findLastStudent(Pageable paging);
}
这将向您的查询中添加“limit”关键字,您可以在控制台中看到。希望这能有所帮助。
@Query(value = "SELECT * FROM students ORDER BY id DESC LIMIT 1", nativeQuery = true) Object getLastStudentDetails();
- Madhu