JPA not saving foreign key to @OneToMany relation

前端 未结 6 1070
小蘑菇
小蘑菇 2020-12-25 13:50

I\'m using Spring with Hibernate as a JPA provider and are trying to get a @OneToMany (a contact having many phonenumbers) to save the foreign key in the phone numbers table

6条回答
  •  感动是毒
    2020-12-25 14:18

    If the Contact-Phone relationship is unidirectional, you can also replace mappedBy in @OneToMany annotation with @JoinColumn(name = "contact_id").

    @Entity
    public class Contact {
      @Id
      private Long id;
    
      @OneToMany(cascade = CascadeType.PERSIST)
      @JoinColumn(name = "contact_id")
      private List phoneNumbers;
    
      // normal getter/setter
      ...
    }
    
    @Entity
    public class PhoneNumber {
      @Id
      private Long id;
    
      ...
    }
    

    Similar in JPA @OneToMany -> Parent - Child Reference (Foreign Key)

提交回复
热议问题