Hibernate-JPA 上多对多关系中的错误

Error in a ManyToMany Relationship on Hibernate-JPA

我在 MySql Workbench 上有一个大型数据库,我正在尝试映射 Eclipse Mars 上实体之间的关系,这要归功于 Hibernate 和 JPA 模块。事实是我收到错误: "In attribute 'personAddresses', the "mapped by“属性 'peopleAdd' 具有此关系的无效映射类型。” 这是涉及的实体。

1

我不得不说做一个正向工程,Hibernate 为我创建一个 AddressId class,其中映射了 Address 的复合主键。我怀疑问题可能是这个,但我不确定,你能帮帮我吗? 在我 post 的代码下,可以更清楚地理解 classes 是如何实现的。

@Entity
@IdClass(AddressId.class)
@Table(schema = "YouDroop", name = "Address")
public class Address implements Serializable
{
...

private Collection<Person> peopleAdd = new HashSet<Person>();

@Id
@Column(name = "Address", length = 45, unique = true, nullable = false)
private String address;
@Id
@Column(name = "Number", unique = true, nullable = false)
private int number;

...

@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(
           name = "PersonHasAddress",
           joinColumns = {
                           @JoinColumn(name = "Address_Address", referencedColumnName = "Address", nullable = false),
                           @JoinColumn(name = "Address_Number", referencedColumnName = "Number", nullable = false)
                           },
           inverseJoinColumns = {@JoinColumn(name = "Person_Email", referencedColumnName = "Email", nullable = false)}
           )
public Collection<Person> getPeopleAddressed(){
    return this.peopleAdd;
}

public void setPeopleAddressed(Collection<Person> people){
    this.peopleAdd = people;
}
}

public class AddressId implements Serializable
{

private String address;
private int number;

public AddressId(){}

public AddressId(String address, int number) {
    super();
    this.address = address;
    this.number = number;
}

...
}

@Entity
@Table(name = "Person", schema = "YouDroop", uniqueConstraints =
{ @UniqueConstraint(columnNames = "NickName"),
@UniqueConstraint(columnNames = "Password") })
public class Person implements Serializable
{
...

private Collection<Address> addresses = new HashSet<Address>();

...

@ManyToMany(fetch = FetchType.LAZY, mappedBy = "peopleAdd")
public Collection<Address> getPersonAddresses(){
    return this.addresses;
}

public void setPersonAddresses(Collection<Address> addresses){
    this.addresses = addresses;
}
}

因为您将@ManyToMany 注释放在了您的getter 方法(或属性)上,而不是在字段上。 mappedBy 属性应该引用 属性 而不是字段。

@ManyToMany
public Collection<Person> getPeopleAddressed() {
...
}

所以你的 mappedBy 属性应该是

@ManyToMany(mappedBy="peopleAddressed")
public Collection<Address> getPersonAddresses() {
...
}