【问题标题】:Get result from query as custom List of Objects从查询中获取结果作为自定义对象列表
【发布时间】:2018-11-06 20:23:03
【问题描述】:

我想为显示过去 10 天每天的交易量的条形图实现 SQL 查询。例如我有这个表结构:

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&lt;DashboardDTO&gt; 的结果?

【问题讨论】:

  • 您想执行原生查询并将结果映射到 java 对象?
  • 是的——这就是我想要得到的结果。
  • 请查看this 文章。特别是DTO projections using a ConstructorResult 部分

标签: java sql jpa spring-data-jpa


【解决方案1】:

简单的方法是将@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();
}

【讨论】:

    猜你喜欢
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 2020-11-14
    相关资源
    最近更新 更多