【问题标题】:How to count records of particular id in spring boot and hibernate如何在spring boot和hibernate中计算特定id的记录
【发布时间】:2015-11-25 04:07:17
【问题描述】:

我正在开发一个使用 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 来查找记录。

这是我的道界面

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

【问题讨论】:

  • 您想计算给定id 的rating 吗?
  • 实际上我的数据库中有评级表。在这张表中,我有 post_id、user_id 和 rating_points 列。 post_id 可以是多个,我想计算给定 post_id 的所有行

标签: java hibernate spring-mvc spring-boot hql


【解决方案1】:

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

EDIT:cmets中的第二个问题:

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

【讨论】:

  • 我正在运行这个查询... "select count(r.id),points from Rating r where r.postId=?1 group by points";我使用 List 作为返回类型.. 我得到结果但没有在结果中得到列名
  • 我应该在这里做什么你能告诉我吗?
  • 试试:select count(r.id), r.points from Rating r where r.post_id=?1 group by r.points
  • 同样的结果...没有得到列名
  • 我无法理解它是哪一列的值
【解决方案2】:
@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;
}

【讨论】:

    猜你喜欢
    • 2017-11-29
    • 2014-09-22
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多