[英]JPA Handle Relationships without Foreign Keys
If I were to have a system that had clients, employees, timesheets, and they all had attachments associated with them. 如果我要拥有一个包含客户,员工,时间表的系统,并且它们都具有与之关联的附件。 Rather than creating an attachment table for every once I want a generic table that would be shared.
而不是为我希望共享的通用表一次创建一个附件表。
| ID | TYPE | FILE_LOCATION | FILE_TYPE | REFERENCED_ID |
| 1 | CLIENT | C:\temp1.pdf | PDF | 22 |
| 2 | TIMESHEET | C:\temp2.pdf | PDF | 342 |
In this case the reference_id would link but wouldn't be a foreign key since it could go to many different tables. 在这种情况下,reference_id将链接,但不是外键,因为它可以进入许多不同的表。
If I wanted all attachments for a particular client I would have SQL like this 如果我想要特定客户端的所有附件,我将拥有这样的SQL
SELECT * FROM ATTACHMENT WHERE TYPE = 'CLIENT' AND REFERENCE_ID = 22;
Can this type of relationships be modeled with JPA / Hibernate? 可以使用JPA / Hibernate建模这种类型的关系吗?
Yes, they can. 是的他们可以。
What you're describing is the mapping for a root Attachment
entity with several sub-entities ( ClientAttachment
, TimesheetAttachment
) using 您要描述的是使用以下几个子实体(
ClientAttachment
, TimesheetAttachment
)的根Attachment
实体的映射
All the sub-entities would have a ManyToOne association with their owning entity (Client, Timesheet), using REFERENCE_ID as join column. 使用REFERENCE_ID作为联接列,所有子实体将与它们各自的实体(客户端,时间表)建立一个ManyToOne关联。
I would rather use an Attachment entity/table, without any REFERENCED_ID column, and several join tables: one for each entity having attachements. 我宁愿使用没有任何REFERENCED_ID列的附件实体/表和几个联接表:每个具有附件的实体一个。 This would be cleaner: real foreign keys could be used, instead of storing the ID of multiple different tables in the same column.
这样会更干净:可以使用真实的外键,而不是将多个不同表的ID存储在同一列中。 It would also avoid the need for all these subclasses.
它还将避免需要所有这些子类。 You would just have a OneToMany association with Attachment in every entity having attachments.
在每个具有附件的实体中,您将只具有一个与附件的OneToMany关联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.