2017-05-23 17 views
1

我公司目前有以下JPA設置:如何使用JPA setMaxResults()(LIMIT 20)沒有實體管理器?

com.example.entities.Employee 
com.example.repository.EmployeeRepository 
com.example.controllers.EmployeeController 

的應用程序設置都指向一個SQL服務器和控制器有沒有問題端點(即「/裝getEmployees」)。

但是,我想限制正在返回的員工數量。

使用JPA後,我沒有使用任何entityManager代碼許多教程建議。

相反,我使用下面的設計模式庫:

com.example.repository.EmployeeRepository

package com.example.repository; 

import java.util.List; 

import org.springframework.data.jpa.repository.JpaRepository; 
import org.springframework.data.jpa.repository.Query; 
import org.springframework.stereotype.Repository; 

import com.example.entities.Employee; 

@Repository 
public interface EmployeeRepository extends JpaRepository<Employee, Long> { 

    @Query("SELECT " 
     + "e.eid, " 
     + "e.firstname, " 
     + "e.lastname, " 
     + "e.dept) " 
     + "FROM Employee e") 
    public List<Employee> getAllEmployees(); 

} 

下面是端點控制文件的副本:

com.example.controllers.EmployeeController

package com.example.controllers; 

import java.util.List; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.ResponseBody; 

import com.example.entities.Employee; 
import com.example.repository.EmployeeRepository; 

@Controller 
public class EmployeeController { 

    @Autowired 
    EmployeeRepository empRepo; 

    @RequestMapping(name = "/getAllEmployees") 
    public @ResponseBody List<Employee> getAllEmployees() { 
     return empRepo.getAllEmployees(); 
    } 

} 

正如你所看到的,是沒有提到的EntityManager在這些文件中,所以它是更加的抽象的情況,在這裏我不知道在那裏我會發起setMaxResults(20)方法不明確使用entityManager

我注意到setMaxResults功能通常被附加到一個查詢對象:

q.setMaxResults(n) 

任何想法?

+0

你能剛修改查詢並添加像'LIMIT 20'? – csmckelvey

+0

你沒有使用EntityManager,所以你沒有使用JPA API,而是使用Spring Data JPA API。標籤固定 –

+0

@csm_dev當JPQL沒有「LIMIT」作爲關鍵字時沒有意義 –

回答

2

如何在Spring數據使用可分頁界面?

package com.example.repository; 

import java.util.List; 

import org.springframework.data.jpa.repository.JpaRepository; 
import org.springframework.data.jpa.repository.Query; 
import org.springframework.stereotype.Repository; 
import org.springframework.data.domain.Page; 
import org.springframework.data.domain.Pageable 

import com.example.entities.Employee; 

@Repository 
public interface EmployeeRepository extends JpaRepository<Employee, Long> { 

    @Query("SELECT " 
     + "e.eid, " 
     + "e.firstname, " 
     + "e.lastname, " 
     + "e.dept) " 
     + "FROM Employee e") 
    public Page<Employee> getAllEmployees(Pageable pageable); 

} 

在你的控制器,你可以設置你想要多少項目獲得:

@RequestMapping(name = "/getAllEmployees") 
public @ResponseBody List<Employee> getAllEmployees() { 
    return empRepo.getAllEmployees(new PageRequest(0, 20)).getContent(); 
} 
+0

這實際上運行良好。謝謝。 –

1

HQL不支持限制功能,所以你有兩個選擇在這裏:

  • 使用原生SQL查詢
  • 使用的EntityManager和setMaxResults
相關問題