JPA:持久化外键约束的问题

时间:2010-07-27 23:19:25

标签: jpa java-ee persistence foreign-keys orm

我有两个实体:

客户实体

@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已成功插入CustomerTom Cruise已成功插入Facility,但在Facility内,CUSTOMER_FK值为null,这表明我失败了坚持外键约束。我在这里做错了什么?

1 个答案:

答案 0 :(得分:8)

CustomerFacility之间的关系是双向关联,必须管理关联的两面。您可以手动执行此操作,但我建议您使用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
}