簡體   English   中英

使用現有記錄的外鍵創建休眠實體

[英]Create hibernate entity with foreign key to existing record

我正在使用休眠4.3.8。 在Java Spring Web應用程序和postgres db中。

我有兩個外鍵來記錄B和C的記錄A。

記錄B已存在於系統中。 記錄C是新記錄,將在保存記錄A時添加。記錄A的布局是這樣的。

A.primaryKey
A.foreignKey to B.primaryKey (already exists in system)
A.foreignKey to C.primaryKey (new record)
A.feildX

如何保存記錄A?

謝謝你的幫助

這是實體類。我是休眠的新手,它解釋了錯誤。

@Entity
@Table(name="atable")
public class Aclass {

    @Id
    @Column(name="arec_id")
    private String id;

    //Do not create a reference to the bclass in this object. however do write the bclass object with a foreign key reference back to this aclass object
?   @Transient
?    @OneToOne(cascade=?)
?    @JoinTable(name="btable",inverseJoinColumns=@JoinColumn(name="brec_id"))
?   private Bclass bclass;

    //Create a reference to the cclass object in this record and write the cclass object as well
    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="crec_foreign_key",referencedColumnName="crec_id")
    private Cclass cclass;

    @Column(name="description")
    private String description;

    private VoiceEngineModel voiceEngineModel;

}

@Entity
@Table(name="btable")
public class Bclass {

    @Id
    @Column(name="brec_id")
    private String id;

    @Column(name="aref")
    private String aref;

    @Column(name="description")
    private String description;


}

@Entity
@Table(name="ctable")
public class Cclass {

    @Id
    @Column(name="crec_id")
    private String id;

    @Column(name="description")
    private String description;


}

我想出了解決方案。 很容易。 Bclass的原始代碼是錯誤的。 抱歉。

  1. 在Aclass中刪除對Bclass的任何引用
  2. 對於Bclass修改列參考

    @Entity @Table(name =“ btable”)公共類Bclass {

    @Id @Column(name =“ brec_id”)私有字符串ID;

    @ManyToOne @JoinColumn(name =“ aref”)私有Aclass aref;

    @Column(name =“ description”)私有字符串描述;

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM