多对多而不是一对多

many-to-many instead of one-to-many

我有点不明白为什么 JPA 创建两个多对多关系而不是 2 个一对多关系。 我有 class 个作者和两个电话和电子邮件集合。

@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;

和两个classes

@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 表。我很困惑。

您的 JPA 提供程序创建了额外的表(author_emailauthor_phone),因为您有双向关系,但您没有指出这些关系的哪一方是所有者(mappedBy 属性).

Author class 中的集合进行以下更改,它应该会按预期工作。

@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;