未在@OneToOne中设置JPA外键

时间:2019-03-05 20:58:43

标签: spring-boot jpa one-to-one

我有一个@OneToOne关系映射。我可以获取记录并查看关系,但是我无法创建记录并保留外键。当前,当在父表(FacilityGeneral)中创建新记录时,我也在ChildTable(FacilityLocation)中创建了一条新记录,但是,子表中的外键不会自动创建。

@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;

我试图通过将在父表(FacilityGeneral)中作为主键创建的序列值分配给子表中的另一个字段来以编程方式对其进行持久化,但是由于在对象被持久化之前不会生成序列号,因此无法进行操作。实际外键字段保持为空。

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);
}

要用父表主键自动填充外键(facilityIdFk),我要缺少什么?

1 个答案:

答案 0 :(得分:1)

凝视了几个小时之后,我意识到cascade = CascadeType.PERSIST必须是cascade = CascadeType.ALL