我相信下面的代碼作業正常,但我的邏輯有缺陷,所以我正在尋求幫助以獲得我真正想要的結果。此外,我認為我對 JPA 方法的嘗試過于復雜,可能有更清潔的解決方案。我知道我可能會使用@Query,但我想嘗試讓方法名稱解決方案也能正常作業,這樣我就可以了解哪里出錯了。
為簡單起見,我在此示例中洗掉了 DB 表,但是我有 Table1 是頂級表,而 Table2 位于它下方,并且有一個外鍵回傳到 Table1。
表 1 -> 表 2 是一對多的關系,我正在尋找一種 JPA 方法,當給定 Table1 ID 和 Table2 中的當前有效記錄時,該方法將從表 1 中拉回一條記錄(這將是 EffectiveDateTime 列是最近的但不是未來的日期)。使用下面的示例,我希望它只拉回 ID 8。
不幸的是,我相信通過我下面的代碼,它可以識別 Table2 的其中一個記錄在所需的日期范圍內,因此將所有與表 1 中的 ID 相關的記錄拉回來。雖然我可能錯了并且邏輯可能以不同的方式存在缺陷。
任何幫助,將不勝感激。
Table1 物體類
@Entity
@Table(name = "TABLE1")
public class Table1 {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", nullable = false, unique = true)
private Integer id;
@OneToMany(mappedBy = "table1", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@Fetch(value = FetchMode.SUBSELECT)
@JsonManagedReference
private List<Table2> table2;
//Plus getters & setters
Table2 物體類
@Entity
@Table(name = "TABLE2")
public class Table2{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", nullable = false, unique = true)
private Integer id;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "Table1Id")
@JsonBackReference
private Table1 table1;
@Column(name = "EffectiveDateTime", nullable = false)
private LocalDateTime effectiveDateTime;
//Plus getters & setters
回購類
@Repository
public interface Repository extends JpaRepository<Table1, Integer>, JpaSpecificationExecutor<Table1> {
public Optional<Table1> findTopByIdAndTable2EffectiveDateTimeLessThanEqualOrderByTable2EffectiveDateTimeDesc(int id, LocalDateTime now);
}
當前 JSON 回傳
{
"id": 5
"Table2": [
{
"id": 6,
"effectiveDateTime": "2021-01-01T00:00:01"
},
{
"id": 8,
"effectiveDateTime": "2022-01-01T00:00:01"
},
{
"id": 9,
"effectiveDateTime": "2023-01-01T00:00:01"
}
]
}
uj5u.com熱心網友回復:
一旦您宣告了 oneToMany 關系,您的物體將在呼叫 getTable 方法時加載所有連接的物體(序列化時由 jackson 呼叫)。我相信如果您激活除錯模式,您將看到 2 個請求,第一個將是您在存盤庫中描述的那個,第二個是 JPA 用來加載所有相關 table2 物體的一個。
他們是一些可能的方法來完成你想要的:
- 第一個(也是最明顯的?)是手動使 2 請求等效于您的 HQL 請求(表 1 按 ID 查找,然后表 2 由...查找),然后聚合 2 個結果
- 第二個是使用杰克遜以你想要的方式序列化你的資料(通過過濾無用的表2資料)
- 第三個是使用jackson將table2(為您提供相應的table1資料)序列化為適當的JSON。如果您的 table1 參考大量 table2 資料,它會更復雜但可能更有效。
- 最后一個是嘗試使用投影,它允許您在請求資料時僅宣告要檢索的資料。
希望這有幫助!
uj5u.com熱心網友回復:
最后,我們使用 JPQL 查詢完成了這項作業。下面是一個查詢示例,以防將來對其他任何人有所幫助。
@Query(value = "SELECT table1 FROM Table1 table1 "
" JOIN FETCH table1.table2 table2 "
" WHERE table1.id = :table1Id"
" AND table2.id = "
" ( SELECT table2.id FROM table2 "
" WHERE table2.table1.id = :table1Id "
" AND table2.effectiveDateTime = "
" ( SELECT MAX(effectiveDateTime) FROM table2"
" WHERE table2.table1.id = :table1Id "
" AND table2.effectiveDateTime <= :currentTimestamp "
" ) "
" ) ")
Optional<Table1> getEffectiveDateTimeTable2(@Param("table1Id") int table1Id, @Param("currentTimestamp") LocalDateTime currentTimestamp);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/497668.html
