I am using Java EE 6. Just want to throw it out there first
Here is the relationship. A customer
can have multiple 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);
}
}
Here is Facility Class
@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
...
}
Now in main if I just have this, then it work fine. I can see this get insert into my database
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();
However, as soon as I try to add facility and force FK constrain. Things start to break.
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();
Here is the error. First I get double of the same "Wake Forest University" customer insert into CUSTOMER table (not name
attribute is not set to unique, it is that it insert two entries at one time into the database). However, nothing get insert into my FACILITY table. Any idea why? One of the error code is Field 'customer_fk' doesn't have a default value
. Maybe that can hint you guys a bit. I have no idea. When I look into the error log :Call: INSERT INTO FACILITY (ID, NAME, STREET2, STREET1, ZIPCODE, STATE, CITY, COUNTRY) VALUES (?, ?, ?, ?, ?, ?, ?, ?)bind => [2, Xia, null, null, null, null, null, null]
, my FACILITY
table, have a field CUSTOMER_FK
, which is created when I try to force one-to-many relationship between CUSTOMER
and FACILITY
, but the query never insert anything into that field