簡體   English   中英

如何在Spring Boot和Hibernate中計算特定ID的記錄

[英]How to count records of particular id in spring boot and hibernate

我正在使用Spring Boot和Hibernate進行項目。 我想根據表中的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>{
}

將此添加到您的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;
}
@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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM