【问题标题】:Group by the Class of Object in JPQL按 JPQL 中的对象类别分组
【发布时间】:2018-12-20 23:45:18
【问题描述】:

带有 JPA 和 JSF 的 JavaEE 应用程序有一个账单实体,它是 BilledBill、CancelledBill 和 RefundBill 的子类。 我使用 EclipseLink 作为持久性提供者。 我想编写一个查询,按类的类型对总数进行分组。 我累了,但失败了。 这可能吗?

相关构造函数如下。

public BillSummery(PaymentMethod paymentMethod, Class billClass, Double total, Double discount, Double netTotal, Double tax, Long count, BillType billType) {
    this.paymentMethod = paymentMethod;
    this.total = total;
    this.discount = discount;
    this.netTotal = netTotal;
    this.tax = tax;
    this.count = count;
    this.billType = billType;
    this.BillClass = billClass;
}

JPQL如下

String j = "select new com.divudi.data.BillSummery(b.paymentMethod, type(b), sum(b.total), sum(b.discount), sum(b.netTotal), sum(b.vat), count(b), b.billType) "
            + " from Bill b "
            + " where b.retired=false "
            + " and b.billTime between :fd and :td "
            + " group by b.paymentMethod, type(b), b.billType";

【问题讨论】:

  • 你是什么意思你失败了 - 你得到一个错误还是出了什么问题?简化您的查询,只需按类型(b)对总数和分组求和,然后从那里开始计算。 “选择 sum(b.total), type(b) as bill_type from Bill b group by bill_type”。构建 JPQL 查询后,查看返回类型并确保它们适合您的构造函数

标签: jpa eclipselink jpql


【解决方案1】:

您使用的是哪种继承策略?

如果它涉及鉴别器列,您始终可以将其映射为常规列,就像任何其他属性一样。然后它将可用于查询。

例子:

@Entity
@Inheritance(strategy = JOINED)
@DiscriminatorColumn(name = "dtype")
public abstract class Bill {

    @Column(name = "dtype", insertable=false, updatable=false)
    private String type;
    ...
}

话虽如此,我会认真考虑扁平化继承结构。听起来好像Bill 可以变成BilledBillCancelledBill,所以也许Bill 拥有status 属性就足够了?

【讨论】:

  • 我已经按照您建议的方式修改了继承。现在无需按类型分组。谢谢
猜你喜欢
  • 1970-01-01
  • 2015-04-12
  • 2020-12-12
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多