首页 > 解决方案 > 使用 JPA 查询获取上个月内的所有列?

问题描述

我当前的查询统计了每个活动售出的所有门票,并列出了门票数量最多的每个活动。现在的问题是,我还需要在上个月内获得所有票,而我根本无法从 JParepo Doc 中获得所需的结果。只要。当前查询如下所示:

@Query("select t.event.id, count(t.id) from Ticket t where t.event.seat = True group by t.event.id order by count(id) desc")

我在想在“真”之后和分组之前需要实施的地方,但我只是不知道如何。如果你们中的某个人能设法帮助我,我将非常感激!

编辑:忘记提及当前事件日期简称为“日期”,因此访问它需要做的只是 t.event.date。

标签: javaspringhibernatejpa

解决方案


将您的查询更改为以下内容:

@Query("select t.event.id, count(t.id) from Ticket t where t.event.seat = ?1 and t.event.date >= ?2  group by t.event.id order by count(t.id) desc")
List<?> getEventCount(Boolean seatTaken, Date eventDate);

我修改了查询以使座位成为布尔参数(如果您想查找未占用的座位,则可重用)并添加到Date参数中。

然后计算一个月前的日期:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
Date date = cal.getTime();

最后实现新方法:

List<?> results = repo.getEventCount(true, date);

要在 spring 中创建一个 Service 类并将它们放在一起,请尝试以下操作:

@Service
public class TicketService {

  @Autowired
  private TicketRepository repo;

  public List<?> getTicketEventCount() {
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MONTH, -1);
    Date date = cal.getTime();

    List<?> results = repo.getEventCount(true, date);
    return results;
  }
}

推荐阅读