JPA Foreign Key Not being Set in @OneToOne

I have a @OneToOne relationship mapped. I can get records and see the relationship but I have not been able to create a record and have the foreign key persist. Currently, When a new record gets created in the parent table (FacilityGeneral) I also create a new record in the ChildTable(FacilityLocation), however, the foreign key in the child table does not get created automatically.

@Entity
public class FacilityGeneral {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "facilityGenIdSeq")
@SequenceGenerator(name = "facilityGenIdSeq", initialValue = 567, allocationSize = 1)
@Column(updatable = false, unique = true)
private Long generalIdPk;

@NotBlank(message = "Facility Name is required")
private String facilityName;

@OneToOne(fetch = FetchType.EAGER, mappedBy = "facilityGeneral", cascade = CascadeType.PERSIST)
@JsonIgnore
private FacilityLocation location;
}


@Entity
public class FacilityLocation {
@Id
@SequenceGenerator(name = "facilityLocationSeq", initialValue = 374, allocationSize = 1)
@GeneratedValue (strategy = GenerationType.SEQUENCE, generator = "facilityLocationSeq")
@Column(updatable= false, nullable = false, unique = true)
private Long locationIdPk;

@OneToOne (fetch = FetchType.EAGER)
@JoinColumn (name="facilityIdFk")
private FacilityGeneral facilityGeneral;

I tried to persist it programmatically by assigning the sequence value being created as the Primary key in parent table (FacilityGeneral) to a differnt field in the Child table but was unable since the Sequence # isn't generated until the object is persisted. The actual foreign key field remained null.

public FacilityGeneral createOrUpdate(FacilityGeneral facility){
    if(facility.getGeneralIdPk() == null) {
        //create new facility
        Number nextInSeq = entityManager.createNativeQuery("SELECT FACILITY_GEN_ID_SEQ.nextval from dual").getFirstResult();
        facility.setGeneralIdPk(nextInSeq.longValue());

        //Create new Records for corresponding relationships
        FacilityLocation location = new FacilityLocation();
        facility.setLocation(location);
        location.setFacilityGeneral(facility);
        //had a none foreignkey field here that I tried to insert to but failed
        //location.setFacilityId(nextInSeq.LongValue());
    }

    return facilityGeneralRepository.save(facility);
}

What am I missing in order to populate the foreign key filed (facilityIdFk) automatically with the parent table primary key?

Upvotes: 0

Views: 2662

Answers (1)

After staring at this for hours I realized that the cascade = CascadeType.PERSIST needed to be cascade = CascadeType.ALL

Upvotes: 1

Related Questions