我有两个实体:
客户实体
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@OneToMany(mappedBy="customer", cascade=CascadeType.ALL)
private List<Facility> facilities;
//Setter and Getter for name and facilities
public void addFacility(Facility facility){
this.facilities.add(facility);
}
}
设施实体
@Entity
public class Facility {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(name="CUSTOMER_FK")
private Customer customer;
private String name;
//Setter and Getter, equals and hashcode
...
}
所以在我的主要内容中我这样做
Customer customer = new Customer();
customer.setName("Wake Forest University");
Facility facility = new Facility();
facility.setName("Tom Cruise");
EntityManager entityManager = Persistence.createEntityManagerFactory("EntityClassPU").createEntityManager();
entityManager.getTransaction().begin();
customer.addFacility(facility);
entityManager.persist(customer);
entityManager.getTransaction().commit();
Wake Forest University
已成功插入Customer
,Tom Cruise
已成功插入Facility
,但在Facility
内,CUSTOMER_FK
值为null,这表明我失败了坚持外键约束。我在这里做错了什么?
答案 0 :(得分:8)
Customer
和Facility
之间的关系是双向关联,必须管理关联的两面。您可以手动执行此操作,但我建议您使用addFacility()
方法执行此操作:
public void addFacility(Facility facility){
if (this.facilities == null) {
this.facilities = new ArrayList<Facility>();
}
this.facilities.add(facility);
facility.setCustomer(this); // that's the part you're currently missing
}