我很担心为什么JPA会创建两个多对多而不是两个一对多的关系。 我有班级作者和两套手机和电子邮件。
@Entity
public class Author {
@Id
@GeneratedValue
private int id;
private String firstName;
private String lastName;
@OneToMany(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
private Set<Phone> phones;
@OneToMany(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
private Set<Email> emails;
和两个班级
@Entity
public class Phone {
@Id
@GeneratedValue
private int id;
private String number;
@ManyToOne
@JoinColumn(name = "author_fk_phone_id")
private Author author;
@Entity
public class Email {
@Id
@GeneratedValue
private int id;
private String email;
@ManyToOne
@JoinColumn(name = "author_fk_id")
private Author author;
因此JPA应该创建Author,Phone,Email表,但JPA还会创建author_email,author_phone表。我很困惑。
答案 0 :(得分:1)
您的JPA提供程序会创建其他表(author_email
和author_phone
),因为您具有双向关系,但您没有指出这些关系的哪一方是所有者(mappedBy
属性)。
对Author
类中的集合进行以下更改,它应该按预期工作。
@OneToMany(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER, mappedBy = "author")
private Set<Phone> phones;
@OneToMany(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER, mappedBy = "author")
private Set<Email> emails;