如何在春季启动和休眠中统计特定id的记录



我正在做一个使用Spring启动和休眠的项目。我想根据表中的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;
}

最新更新