我正在使用 Java EE 6。只是想先把它扔出去
。这就是关系。Acustomer
可以有多个facility
Here is Customer Class
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="CUSTOMER_FK", nullable=false)
private List<Facility> facilities;
public Customer(){
facilities = new ArrayList<Facility>();
}
public Customer(Long id, String name, List<Facility> facilities) {
this.id = id;
this.name = name;
this.facilities = facilities;
}
//set and get method
...
public void addFacility(Facility facility){
this.facilities.add(facility);
}
}
这里是设施类
@Entity
public class Facility {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public Facility(){}
public Facility(Long id, String name, Address address, List<Project> project) {
this.id = id;
this.name = name;
}
//Set and get method
...
}
现在主要是如果我只有这个,那么它工作正常。我可以看到这个被插入到我的数据库中
Customer customer = new Customer();
customer.setName("Wake Forest University");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("EntityLibraryPU");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(customer);
tx.commit();
但是,一旦我尝试添加设施并强制 FK 约束。事情开始破裂。
Customer customer = new Customer();
customer.setName("Wake Forest University");
Facility facility = new Facility();
facility.setName("Xia");
customer.addFacility(facility);
EntityManagerFactory emf = Persistence.createEntityManagerFactory("EntityLibraryPU");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(customer);
tx.commit();
这是错误。首先,我将相同的“维克森林大学”客户插入 CUSTOMER 表的两倍(不是name
属性未设置为唯一,而是一次将两个条目插入数据库)。但是,我的 FACILITY 表中没有任何内容。知道为什么吗?错误代码之一是Field 'customer_fk' doesn't have a default value
。也许这可以暗示你们一点。我不知道。当我查看错误日志时:Call: INSERT INTO FACILITY (ID, NAME, STREET2, STREET1, ZIPCODE, STATE, CITY, COUNTRY) VALUES (?, ?, ?, ?, ?, ?, ?, ?)bind => [2, Xia, null, null, null, null, null, null]
,我的FACILITY
表有一个字段,当我尝试强制andCUSTOMER_FK
之间的一对多关系时创建该字段,但查询从未在该字段中插入任何内容CUSTOMER
FACILITY