2015-08-31 31 views
1

我正在使用Spring開機和休眠的項目。我想計算表中的ID與記錄。我可以統計表中的所有記錄,但無法對外鍵計數記錄。如何計算特定ID在春季開機和休眠的記錄

這裏是我的控制器代碼

@RequestMapping("/rating/{id}") 
@ResponseBody 
public long getRatingInfo(@PathVariable("id") long id, HttpServletRequest req, HttpServletResponse res) throws Exception { 

long postobj = myDao.count(); 
return postobj; 
} 

我在這裏通過在URL中id但沒有的count方法通過這個ID查找記錄。

這裏是我的DAO接口

@Transactional 
public interface MyDaoInterface extends CrudRepository<Rating, Long>{ 
} 
+0

你想對給定'id'算rating'的'? – SWiggels

+0

其實我在我的分貝有評級表。在這個表中,我有post_id,user_id和rating_points列。 post_id可以是多個,我想要計算給定的所有行post_id –

回答

2

添加到您的DAO:

@Query(countByPostId) 
Integer countByPostId(Long post_id); 

final String countByPostId= "SELECT COUNT(ra) FROM Rating ra WHERE ra.post_id = ?1" 

而且也把它叫做:

@RequestMapping("/rating/{id}") 
@ResponseBody 
public long getRatingInfo(@PathVariable("id") long id, HttpServletRequest req, HttpServletResponse res) throws Exception { 

long postobj = myDao.countByPostId(id); 
return postobj; 
} 

編輯:在第二個問題評論:

@Transactional 
public interface MyDaoInterface extends CrudRepository<Rating, Long>{ 
    List<Rating> findByPostId(Long id); 
} 

和來電者:

@RequestMapping("/rating/{id}") 
@ResponseBody 
public long getRatingInfo(@PathVariable("id") long id, HttpServletRequest req, HttpServletResponse res) throws Exception { 

List<Rating> ratings = myDao.findByPostId(id); 
long postobj = ratings.size() //use this code where you effectively need the # of entires. 

return ratings; 
} 
+0

Thanx bro它的工作:) –

+0

我正在運行此查詢...「select count(r.id),點評r從哪裏r.postId =? 1分組「;而我使用列表作爲返回類型..我得到的結果,但沒有得到列名稱的結果 –

+0

我應該在這裏做什麼,你能告訴我嗎? –