简体   繁体   English

从查询中获取结果作为自定义对象列表

[英]Get result from query as custom List of Objects

I want to implement SQL query for Bar chart which shows volumes per day for last 10 days. 我想对条形图实施SQL查询,该条形图显示最近10天每天的交易量。 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: 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 Object: 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;
    }
}

How I can implement the query properly? 如何正确实施查询? I would like to get the result as List<DashboardDTO> without using Entity? 我想在不使用Entity的情况下以List<DashboardDTO>获取结果吗?

The simple way is add @Entity , @Id to your DashboardDTO and make your native sql alias name match the DTO's property name. 简单的方法是将@Id @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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM