0

I have an entity class which I need to use at multiple places. So I created a class with generics as below

class Output<T> {
    ...
    private String referencedEntityName; 
    private T referencedEntity; 
    ...

}

I've two other classes which are using this class

class Process {
     ...
     private List<Output<Process>> outputs;
     ...
}

Another class which uses Output<T> is

class Machine {
    ...
    private List<Output<Machine>> outputs; 
    ...

}

When stored in database it should look like this

+----+------------------------+----------------------+
| id | referenced_entity_name | referenced_entity_id |
+----+------------------------+----------------------+
| 1  | Process                | 123                  |
+----+------------------------+----------------------+
| 2  | Process                | 234                  |
+----+------------------------+----------------------+
| 3  | Machine                | 345                  |
+----+------------------------+----------------------+

How do I achieve this?

P. S. This is not exactly an inheritance problem like this. Though it could be solved using an interface solution like DiscriminatorValue but I'm not sure.

Here, there is a relation between two entities, one entity is referred in a few other entities. I think that should be clear by the use of generics. Also, this solution could be designed in some other way by maintaining the same relations. I'm open to that as well.

Ganesh Satpute
  • 3,664
  • 6
  • 41
  • 78
  • Possible duplicate of [When to use DiscriminatorValue annotation in hibernate](https://stackoverflow.com/questions/16772370/when-to-use-discriminatorvalue-annotation-in-hibernate) – XtremeBaumer Mar 06 '19 at 12:19
  • 1
    please make question clear , not understandable title , many to one bidirectional ? – Mithat Konuk Mar 06 '19 at 12:21
  • @XtremeBaumer I think it's not duplicate. I'm not using inheritance here. I'm using relation with generics – Ganesh Satpute Mar 08 '19 at 05:21
  • @MithatKonuk Yes. Many to one bidirectional relationship with generics – Ganesh Satpute Mar 08 '19 at 05:21
  • [This](https://stackoverflow.com/questions/35937644/generics-with-hibernate/35938380) and [that](https://stackoverflow.com/questions/7000428/using-hibernate-with-generics). 2 more questions which already deal with generics in hibernate. It definitly looks like you need `@Any` relationship – XtremeBaumer Mar 08 '19 at 07:17

1 Answers1

1

Read about inheritance in JPA. With inheritance strategy SINGLE_TABLE you will get exactly table like you posted. See https://en.wikibooks.org/wiki/Java_Persistence/Inheritance#Example_single_table_inheritance_table_in_database

Peter Šály
  • 2,848
  • 2
  • 12
  • 26