I want to implement SQL query for Bar chart which shows volumes per day for last 10 days. For example I have this table structure:
CREATE TABLE `payment_transactions` (
`id` int(11) NOT NULL,
`amount` int(11) DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
);
I get this example result (grouped per day):
Date | Amount| Number of transactions per day |
11-11-2018 | 30 | 3 |
11-12-2018 | 230 | 13 |
JPA query:
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 Object:
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;
}
}
How I can implement the query properly? I would like to get the result as List<DashboardDTO>
without using Entity?
The simple way is add @Entity
, @Id
to your DashboardDTO
and make your native sql alias name match the DTO's property name.
@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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.