I want to use Hibernate with JPA to do a join between three tables, like this:
Tables: [primary key in square brackets]
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)
To be clear, this means that tools on different toolbelts having the same tool_id can have different names.
This is the SQL query I want:
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
How do I do such a thing with JPA?
From my prespective that tool_id is out of place, because you cant get tool from only its tool_id, its better to call that tool_type or something like that. In this case just use embeddable class as composite id
you should have class like this
@Embeddable
public class ToolPK implements Serializable {
@ManyToOne
@JoinColumn(name = "TOOLBELT_ID")
private Toolbelt toolbelt;
private Long toolType;
//(getter setter here)
}
Then use it in the Tool class as primary key
@EmbeddedId
private ToolPK toolPK;
//this is the real tool_id
//not like tool_type which cant get you the object Tool without the toolbelt
Then you only need to put tool_type in the user, not tool_id(because tool_id is composite).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.