A polymorphic association is similar to a foreign key or many-to-one relationship, with the difference that the target can be one of several types (classes in the language, tables in db).
I am transferring a database design that I have been using for several years from PHP to Java. In the old code, I deployed my own ORM, which was not optimal for a number of reasons. Although I could start customizing things later and maybe re-implement my things, while I would like to use ready-made ORM and JPA for my entity classes.
Now, one thing about the database layout that I donโt know how to express in JPA:
I have a Node and Edge table that stores the graph (DAG, if that matters). Each node may optionally refer to a different object from the database. These entites can be negotiated several times throughout the schedule, and there can also be โorphanedโ entites that will not be available to the user, but which may make sense at least for some time.
These objects are not related at all in terms of inheritance, etc., but have a natural hierarchy similar to Customer-> Site-> Floor-> Room. In fact, many years ago, I started with only the foreign key fields pointing to the "parent" objects. However, this hierarchy is not flexible enough and began to fall apart.
For example, I want to allow users to group objects in folders, some objects may have several "parents", as well as changes over time. I need to keep track of how the relationship was, so the edegs chart has a time slot associated with them that indicates when and when this edge was valid.
The link from the node to the object is stored in two columns of the node table, one contains the identifier in the external table, one has its own name. For example (some columns are omitted):
table Node: +--------+-------+----------+ | ixNode | ixRef | sRefType | +--------+-------+----------+ | 1 | NULL | NULL | <-- this is what a "folder" would look like | 2 | 17 | Source | | 3 | 58 | Series | <-- there seven types of related objects so far +--------+-------+----------+ table Source (excerpt): +----------+--------------------+ | ixSource | sName | +----------+--------------------+ | 16 | 4th floor breaker | | 17 | 5th floor breaker | | 18 | 6th floor breaker | +----------+--------------------+
There may be a different solution than using JPA. I could change something in the layout of the table or introduce a new table, etc. However, I already thought a lot about this, and it seems to me that the table structure suits me. Perhaps there is a third way that I did not think about.