我有一个实体:

@Entity
@Table(name = "votes")
public class Vote extends AbstractBaseEntity implements Serializable {
    private static final long serialVersionUID = 1L;

    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    private LocalDate date = LocalDate.now();

    @JsonIgnore
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "restaurant_id", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    private Restaurant restaurant;

    @JsonIgnore
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id", nullable = false)
    private User user;

    public Vote() {
    }

    public Vote(User user, Restaurant restaurant) {
        this.user = user;
        this.restaurant = restaurant;
    }

    //getters and setters
}


我使用Spring Data Repository处理实体,并且有一种方法可以计算餐厅的票数:

@Repository
public interface VoteRepository extends CrudRepository<Vote, Integer> {

    Integer countByRestaurantId(Integer restaurantId);
}


现在,我想从控制器获取投票的统计信息,例如-我可以得到HashMap <LocalDate, Integer>,其中Integer是特定日期的投票计数:

@RestController
@RequestMapping(value = ADMIN_VOTES_URL, produces = JSON_TYPE)
public class AdminVoteController implements Controller {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private VoteService voteService;

    @GetMapping("/statistics")
    public Map<LocalDate, Integer> getVoteStatistics(@PathVariable Integer restaurantId) {
        log.info("get count of the votes for restaurant {}", restaurantId);
        return voteService.getVoteStatistic(restaurantId);
    }
}


那是我对存储库的不成功请求:

@Query("select distinct v.date, count(v.id) from Vote v where v.restaurant.id = ?1 group by v.date")
    Map<LocalDate, Integer> findAllByDateAndRestaurantId(Integer restaurantId);


如何使用Spring Data做到这一点?您也可以为我提供另一种方式,谢谢!

最佳答案

这是修复它的最简单方法!

1)创建DTO:

public class VoteTo implements Serializable {

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate date;

    private Long count;

    public VoteTo() {
    }

    public LocalDate getDate() {
        return date;
    }

    public void setDate(LocalDate date) {
        this.date = date;
    }

    public Long getCount() {
        return count;
    }

    public void setCount(Long count) {
        this.count = count;
    }

    public VoteTo(LocalDate date, Long count) {
        this.date = date;
        this.count = count;
    }
}


2)在同一存储库中,我创建了此方法

@Query("select new ru.topjava.graduation.model.dto.VoteTo(v.date, count(v.id)) from Vote v " +
" where v.restaurant.id = ?1 group by v.date")
List<VoteTo> groupCountByData(Integer restaurantId);


其中ru.topjava.graduation.model.dto.VoteTo是我的DTO类的完整方法(包+类的名称)

10-06 07:27