Java – JPA subclasses referenced by multiple different parent classes
•
Java
I encountered the following ORM problems:
I have two grades A and B, and they all have a group of grades C:
class A { @Id @GeneratedValue private long id; @OneToMany private Set<C> cSet; } class B { @Id @GeneratedValue private long id; @OneToMany private Set<C> cSet; } class C { @Id @GeneratedValue private long id; }
My idea is to use mappedsuperclass for C and have two extension classes, each referenced in a or B But from an object - oriented point of view, this is not the best approach, although I can use superclass types to work with them
Is there a better way to implement this model?
Thank you, Benjamin
Solution
If no mapping annotation is specified (that is, joincolumn or jointable), it uses a join table for each association
Therefore, you will have the following table:
A : id B : id C : id A_C : a_id,c_id (where c_id is unique) B_C : a_id,c_id (where c_id is unique)
If you annotate each set with the joincolumn annotation, the alternative is:
class A { @OneToMany @JoinColumn(name = "a_id") private Set<C> cSet; } class B { @OneToMany @JoinColumn(name = "b_id") private Set<C> cSet; }
Therefore, you will have the following table:
A : id B : id C : id,a_id,b_id
This is of course described in the documentation
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码