简体   繁体   English

映射到许多值

[英]mappedBy to many values

I have this error我有这个错误

mappedBy reference an unknown target entity property mappedBy 引用了一个未知的目标实体属性

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 !我知道问题是什么,我应该将 mappeby 值设为“person”而不是 person1 和 person2,但问题是我在 class 中有 2 个类型为 person (person1,person2) 的变量。姓名 !

in class Person在 class 人

@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY, mappedBy = "person")
private Set<Contact> contact = new HashSet<>();

in class Contact在 class 联系

@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我的 MCD:在此处输入图像描述

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. mappedBy用于表示现有关系的引用方,因此在 JPA 中,您不能真正将 map 它同时指向两个关系。 You'll have to define mappedBy attribute separately for person1 and person2 .您必须分别为person1person2定义mappedBy属性。 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 .但这仅适用于只读访问,您必须使值与contactOnecontactTwo的值保持同步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM