我有两个实体:
客户实体
@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,这表明我无法持久保留外键约束。我在这里做错了什么? 最佳答案
您在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
}