我想对条形图实施SQL查询,该条形图显示最近10天每天的交易量。例如,我有这个表结构:
CREATE TABLE `payment_transactions` (
`id` int(11) NOT NULL,
`amount` int(11) DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
);
我得到了示例结果(每天分组):
Date | Amount| Number of transactions per day |
11-11-2018 | 30 | 3 |
11-12-2018 | 230 | 13 |
JPA查询:
public List<DashboardDTO> findAll() {
String hql = "SELECT date(created_at) AS cdate, sum(amount) AS amount, count(id) AS nooftransaction "
+ "FROM payment_transactions WHERE date(created_at)>=date(now()- interval 10 DAY) "
+ "AND date(created_at)<date(now()) GROUP BY date(created_at)";
TypedQuery<DashboardDTO> query = entityManager.createQuery(hql, Merchants.class);
List<DashboardDTO> data = query.getResultList();
return data;
}
Java对象:
public class DashboardDTO {
private Date date;
private int amount;
private int number_of_transactions;
public DashboardDTO(Date date, int amount, int number_of_transactions) {
this.date = date;
this.amount = amount;
this.number_of_transactions = number_of_transactions;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public int getNumber_of_transactions() {
return number_of_transactions;
}
public void setNumber_of_transactions(int number_of_transactions) {
this.number_of_transactions = number_of_transactions;
}
}
如何正确实施查询?我想不使用实体就得到List<DashboardDTO>
的结果吗?
答案 0 :(得分:0)
简单的方法是将@Entity
,@Id
添加到您的DashboardDTO
,并使您的本机sql别名与DTO的属性名称匹配。
@Entity
public class DashboardDTO {
@Id
private Date cdate;
private int amount;
private int numberOfTransactions;
...
}
public List<DashboardDTO> findAll() {
String hql = "SELECT ... AS cdate, ... AS amount, ... AS number_of_transactions FROM ...";
return entityManager.createNativeQuery(hql, DashboardDTO.class).getResultList();
}