I met the following ORM problem:
I am having two classes A and B who both are having a Set of class 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;
}
One idea I had was using a MappedSuperclass for C and having two extended classes that are each referenced in either A or B. But from an object oriented point of view this is not the nicest approach although I could use the superclass type in order to work with them.
Is there any nicer way to realize this model?
Thanks, Benjamin
If you don't specify any mapping annotation (i.e. JoinColumn or JoinTable), it will use a join table for each association.
You will thus have the following tables:
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)
The alternative if to annotate each set with a JoinColumn annotation:
class A {
@OneToMany
@JoinColumn(name = "a_id")
private Set<C> cSet;
}
class B {
@OneToMany
@JoinColumn(name = "b_id")
private Set<C> cSet;
}
And you will thus have the following tables:
A : id
B : id
C : id, a_id, b_id
This is of course described in the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With