In case you are working with spring-data you should use the Pageable Interface. A sample code below,
My Service,
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
@Service
public class MyModelService {
@Autowired
private MyModelRepository myModelRepository;
@Transactional
public Page<MyModel> findMyModelTop5() {
return myModelRepository.findMyModelTop5(new PageRequest(0, 5));
}
}
My Repository,
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
@Repository
public interface MyModelRepository extends JpaRepository<MyModel, Integer> {
@Query("SELECT mm FROM MyModel mm")
public Page<MyModel> findMyModelTop5(Pageable pageable);
}
You can find a more complete answer about the spring data available options here.