Hibernate一对一关系错了

时间:2014-06-27 18:02:57

标签: java spring hibernate

我有这种关系

    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "candidacy")
@XmlElement
@Getter
@Setter
private InformCandidacy informCandidacy;



    @OneToOne
@JoinColumn(name = "candidacy_id", nullable = false, insertable = false, updatable = false)
@Getter
@Setter
private Candidacy candidacy;

在数据库中我声明了我的FK

                <addForeignKeyConstraint baseColumnNames="candidacy_id" baseTableName="inform_candidacy" constraintName="fk_candidacy_inform_candidacy"   onDelete="CASCADE" onUpdate="CASCADE" referencedColumnNames="id" referencedTableName="candidacy"/>

但是当我尝试继续使用级联Candidacy然后保存第一次在数据库上不存在的InformCandidacy时,它们之间的关系不会被创建,而且Candidacy的InformCandidacy为空

    @Override
public void saveAll(final List<Candidacy> candidacies) {
    for (Candidacy candidacy : candidacies) {
        Candidacy candidacyDB = findById(candidacy.getId());
        candidacy.getInformCandidacy().setCandidacy(candidacyDB);
        candidacyDB.setInformCandidacy(candidacy.getInformCandidacy());
        candidacyRepository.save(candidacyDB);
    }
}

在我的InformCandidacy表中,我没有与Candidacy的关系

       *************************** 1. row ***************************
            id: 101
      candidacy_id: NULL <--------- WTF!
     selected_number: NULL
     information_letter: NULL
    selection_decision: NULL
     selectionReport: 2014-06-28

我做错了什么。

问候。

1 个答案:

答案 0 :(得分:1)

您的映射告诉hibernate不插入或更新&#34; candidacy_id&#34; column(insertable = false,updatable = false)。试试这种方式:

@OneToOne
@JoinColumn(name = "candidacy_id", nullable = false)
@Getter
@Setter
private Candidacy candidacy;