Search code examples
javapersistencemanaged-beanone-to-one

How to persist two entities at the same time with @OneToOne relationship?


I have two entities Travel and Assurance with @OneToOne relationship. Both entities must be created via the same interface with a Save botton. I use this method:

ManagedBean.java:

public String add(){
    newTravel = manager.createTravel(arrivalDate, returnDate, lengthToStay, addToStay, visitPurpose);
    newAssurance = manager.createAssurance(company, assuranceStart, assuranceEnd, newTravel);
    return "Travellers";
}

In the database, I found the Travel_Id associated to the Assurance but The Assurance_Id is null in the Travels Table.


Solution

  • It seems that your relationship is not bilateral (i.e you do not use the mappedBy annotation property). If you used one, you would have only one column (either Travel_Id or Assurance_Id, depending where you put the mappedBy).

    Also consider doing the saving inside the same transaction, e.g by using the same manager method and setting both side of the relationship.