当前位置: 动力学知识库 > 问答 > 编程问答 >

java - How to count records of particular id in spring boot and hibernate

问题描述:

I am working on a project using Spring boot and hibernate. I want to count records against an id in table. I can count all records of the table but unable to count records against a foreign key.

Here is my controller code

@RequestMapping("/rating/{id}")

@ResponseBody

public long getRatingInfo(@PathVariable("id") long id, HttpServletRequest req, HttpServletResponse res) throws Exception {

long postobj = myDao.count();

return postobj;

}

Here i am passing an id in url but there is no method of count to pass this id to find records.

And here is my Dao Interface

@Transactional

public interface MyDaoInterface extends CrudRepository<Rating, Long>{

}

网友答案:

Add this to your DAO:

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

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

And call it likewise:

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

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

EDIT: the second question in the comments:

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

and your caller:

@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;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: