Reputation: 6606
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.
If I wanted all attachments for a particular client I would have SQL like this
SELECT * FROM ATTACHMENT WHERE TYPE = 'CLIENT' AND REFERENCE_ID = 22;
Can this type of relationships be modeled with JPA / Hibernate?
Upvotes: 0
Views: 864
Reputation: 691635
Yes, they can.
What you're describing is the mapping for a root Attachment
entity with several sub-entities (ClientAttachment
, TimesheetAttachment
) using
All the sub-entities would have a ManyToOne association with their owning entity (Client, Timesheet), using REFERENCE_ID as join column.
I would rather use an Attachment entity/table, without any REFERENCED_ID column, and several join tables: one for each entity having attachements. This would be cleaner: real foreign keys could be used, instead of storing the ID of multiple different tables in the same column. It would also avoid the need for all these subclasses. You would just have a OneToMany association with Attachment in every entity having attachments.
Upvotes: 1