我試圖想出一種基于相同基本物體實作多個報告頁面的好方法。
想象一下,我想要根據汽車的一些復雜屬性生成多個報告 - 基本相同SELECT且相同FROM但具有不同的復雜WHERE子句。
報告示例:
- R1:在 B 到 C 期間進行檢查的所有品牌 A 汽車的清單,安裝了 D 件,在 E 國使用。
- R2:今年生產的所有汽車清單
- ...
- R20:串列...
最重要的是,我想要一個過濾組件來幫助查找特定案例。我們可以假設所有這些報告的過濾組件都相同,因為所有報告的欄位/列(幾乎)都相同。
最直接的解決方案是使用所有陳述句創建 20 個視圖,創建 20 個物體來映射這些 DB 視圖,并為所有這些視圖創建存盤庫。但我想這可以通過更聰明的方式實作。
我最初的想法是創建一個CarReportBaseEntity包含大約 50 個欄位/列的基本物體。
@Entity
@Table(name = "CAR_REPORT_VIEW")
public abstract class CarReportBaseEntity<T extends CarReportBaseEntity<T>> implements Serializable, FilteredEntity<T> {
@Id
@Column(insertable = false, updatable = false)
private Long id;
@Column(insertable = false, updatable = false)
private Long manufacturedYear;
etc...
}
然后對于每個不同的報告,我只會創建一個物體,如:
@Entity
@Where(clause = "manufacturedYear = 2020")
class ManufacturedIn2020ReportEntity extends CarReportBaseEntity<ManufacturedIn2020ReportEntity> {
}
其他報告也類似:
@Entity
@Where(clause = "some complex where clause")
class SomeOtherReportEntity extends CarReportBaseEntity<SomeOtherReportEntity> {
}
This would allow me to quickly create new reports by just adding one class and by tweaking the @Where annotation, including all the functionalities shared by the FilteredEntity. However this doesnt work since it creates a @Inheritance(strategy = InheritanceType.SINGLE_TABLE) by default, which then breaks the whole application since I don't have any DTYPE column specified. I don't want to need to specify anything, I just want to create classes for the same Entity but with different complex where clauses.
What could I do to solve this in an elegant way?
uj5u.com熱心網友回復:
您只需要:
- 您已經擁有 CarReportBaseEntity 的物體類
- 創建 20 個 CriteriaQueries 的工廠,其中包含每個報告的jpa標準
- 一堆獲取 CriteriaQuery 引數并添加進一步過濾的(服務)方法(例如。
whereCarBrandStartsWith(CriteriaQuery q, String prefix))
要獲得報告,您需要獲得該報告的 CriteriaQuery 物件并獲得該結果串列。如果您需要進一步過濾這些結果,您可以將標準物件傳遞給您想要的服務方法
編輯1:
我們真的會從多個類中受益,從那時起我們可以為每個報告案例擴展具有特定列/順序的 FilterEntity
您的條件查詢不必總是回傳 CarReportBaseEntity。對于每個報告,您可以定義您想要的任何選擇子句(CriteriaQuery::multiselect)并將結果包裝在您想要的任何 dto 中(CriteriaBuilder::createQuery(resultType))。我在這種方法中看到的優點是,您可以將所有查詢邏輯保存在工廠中的一個地方,而不是將其拆分為 20 個類和多個注釋之一。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314630.html
標籤:java hibernate jpa inheritance
上一篇:為實作相同介面的類創建默認方法
