views:

105

answers:

1

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?

+2  A: 

Your relation between Customer and Facility is a bi-directional association, you must manage both sides of the association. You can do this manually but I suggest doing it in the addFacility() method:

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
}
Pascal Thivent
you are awesome. Thanks man :D
Harry Pham
@HarryPham: You're welcome!
Pascal Thivent