I got two Entity:
Customer Entity
@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);
}
}
Facility Entity
@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
...
}
So in my main I do this
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
is successfully insert into Customer
, and Tom Cruise
is successfully insert in Facility
, however inside Facility
, the CUSTOMER_FK
value is null, which suggest that I fail persist the foreign key contraint. What did I do wrong here?