Search code examples
javahibernatespring-mvcspring-boothql

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>{
}

Solution

  • 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;
    }