2017-08-02 223 views
-2

我怎樣才能得到所有對象從CrudRepository春季

@RequestMapping(value="/test", method=RequestMethod.GET) 
public ModelAndView recoverPass(@RequestParam("num") int num) { 
    ModelAndView mv = new ModelAndView("test"); 
    mv.addObject("lists",appRepo.findAll(num)); 
    return mv; 
} 

我的瀏覽器,但沒有結果輸入http://localhost:8080/test?num=40數據庫。 (int)

回答

1

Spring中的CrudRepository沒有一個名爲findAll()的方法,它接受一個整數參數。沒有參數的findAll()返回所有的對象,而不僅僅是給定的一個特定的整數ID。

你需要弄清楚你想要什麼。如果你想要所有的對象,然後調用沒有參數的findAll(),並擺脫int參數。

如果您只想找到給定整數id的特定對象,請改爲使用findOne(num)。

+0

謝謝,我想找到具有特定字段值的所有對象 –

+0

@RayEn,那麼你應該使用'match'查詢 – sunkuet02

+0

@RayEn如果你想這樣做,那麼你將需要使用Spring數據查詢方法。假設你的字段被稱爲帶有字符串值的foo,然後向你的appRepo接口添加一個名爲findByFoo(String foo)的方法,並且Spring數據會神奇地使它適用於你。 – Plog

0

在Spring中CrudRepository只有findAll()方法巫婆返回從表中的所有項目。 如果你想獲得的所有項目,你應該使用

appRepo.findAll(); 

,或者你應該需要的條件申報方法:

@Repository 
public interface AppRepo extends CrudRepository<Foo, Long> { 
    List<Foo> findBySomeValue(String someValue); 
} 

,並用它在你的邏輯appRepo.findBySomeValue('bar');

0

我認爲你正在嘗試獲得id = 40的用戶。如果您使用spring引導的spring數據jpa,則可以創建一個存儲庫,如userRepository,並創建一個方法findById()以獲取特定id的用戶。

public interface UserRepository extends JpaRepository<User, Serializable>{ 
    User findById(Long id); 
} 

然後可以自動裝配在服務UserRepository並調用findById()方法。您也可以使用相同的UserRepository對象通過調用findAll()方法來獲取所有用戶列表。