I have this error
mappedBy reference an unknown target entity property
I know what is the problem is that I should make the mappeby value "person" istead of person1 and person2 but the probleme is that I have 2 variable of type person (person1,person2) in class Contact I can't name them the same name !
in class Person
@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY, mappedBy = "person")
private Set<Contact> contact = new HashSet<>();
in class Contact
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id_person", nullable = false)
private Person person1;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id_person", nullable = false)
private Person person2;
my MCD : enter image description here
mappedBy
is used to denote the referencing side of an existing relationship, so you can't really map it to two relationships at the same time in JPA. You'll have to define mappedBy
attribute separately for person1
and person2
. What you could do to get both values in one attribute would be to define a transient attribute and join them in the entity manually. Something like:
@Entity
public class Person {
// Other attributes
@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY, mappedBy =
"person1")
private Set<Contact> contactOne = new HashSet<>();
@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY, mappedBy =
"person2")
private Set<Contact> contactTwo = new HashSet<>();
@Transient
private Set<Contact> allContacts;
public Person() {
this.allContacts = new HashSet<>(contactOne);
allContacts.addAll(contactTwo);
}
}
But this is only for read-only access and you would have to keep the value synchronized with values of contactOne
and contactTwo
.