簡體   English   中英

使用JPA從兩個表聯接到第三個表中的組合鍵

[英]Join from two tables to composite key in third table with JPA

我想將Hibernate與JPA結合使用,在三個表之間進行聯接,如下所示:

表格:[方括號中的主鍵]

Worker: ([worker_id], tool_id, site_id)
Toolbelt: ([toolbelt_id])
Site: ([site_id])
SiteToolbelt: ([site_id], toolbelt_id)
Tool: ([toolbelt_id, tool_id], tool_name)

明確地說,這意味着具有相同tool_id的不同工具帶上的工具可以具有不同的名稱。

這是我想要的SQL查詢:

SELECT * FROM Worker w
JOIN SiteToolbelt st ON w.site_id = st.site_id
JOIN Tool t ON t.toolbelt_id = st.toolbelt_id AND t.tool_id = w.tool_id

我如何用JPA做這樣的事情?

從我的角度來看,tool_id不合適,因為您無法僅從其tool_id獲取工具,因此最好調用該tool_type或類似的名稱。 在這種情況下,只需將embeddable類用作復合ID

你應該有這樣的課

@Embeddable
public class ToolPK implements Serializable {
    @ManyToOne
    @JoinColumn(name = "TOOLBELT_ID")
    private Toolbelt toolbelt;
    private Long toolType;
//(getter setter here)
}

然后在Tool類中將其用作主鍵

@EmbeddedId
private ToolPK toolPK;
//this is the real tool_id 
//not like tool_type which cant get you the object Tool without the toolbelt

然后,您只需要在用戶中輸入tool_type即可,而無需在tool_id中輸入(因為tool_id是復合的)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM