亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Hibernate 沒有插入外鍵 ManyToOne 實體

Hibernate 沒有插入外鍵 ManyToOne 實體

胡子哥哥 2022-07-14 09:54:31
我想知道為什么 Hibernate 沒有將外鍵插入數據庫。我在 2 個類之間有 OneToMany 和 ManyToOne 關系。@Entity@Datapublic class Bestelling {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    @JoinColumn(name = "bestelling_id")    private long bestellingID;    private Date bestelDatum;    @ManyToOne    @JoinColumn(name = "account_id")    private Account accountID_fk;    @JoinColumn(name = "adres_id")    @OneToOne    private Adres afleverAdres;    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "bestelling")    private List<Bestellingsregel> bestellingsregels = new ArrayList<>();}和@Entity@Datapublic class Bestellingsregel {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    @JoinColumn(name = "bestellingsregel_id")    private long bestellingsregelID;    private int aantal;    private double prijs;    @ManyToOne(cascade = CascadeType.ALL)    @JoinColumn(name = "bestelling_id")    private Bestelling bestelling;    @OneToOne    @JoinColumn(name = "product_id")    private Product productID;}我正在使用 Postman 將數據插入我的 MySql 數據庫:{"bestelDatum" : "2019-02-28","accountID_fk" : {                    "accountID" : 1                 },"afleverAdres" : {                    "adres_id" : 1                },"bestellingsregels" : [                    { "aantal" : 5,                      "prijs" : 100.50,                      "productID" : { "productID" : 1 }                    }                    ]}它正在向數據庫中插入。唯一的問題是它沒有在表 Bestellingsregel 中設置 bestelling_id。知道我在這里做錯了什么嗎?提前致謝。編輯:我正在使用 Spring,并且 crud 函數位于此界面中:public interface BestellingRepository extends JpaRepository<Bestelling, Long> {}
查看完整描述

2 回答

?
慕斯709654

TA貢獻1840條經驗 獲得超5個贊

您在 Bestellingsregel 將 Bestelling 和 Bestellingsregel 之間的關系定義為與擁有方(持有外鍵)的雙向關系,這是正確的,但有利也有弊。

您有以下選擇:

  1. 使用定義的關系并將 Bestelling 對象設置為列表中的每個 Bestellingsregel 對象。Bestellingsregel 是擁有方,因此您必須在保存前直接設置參考。

  2. 使您的關系單向:從 Bestellingsregel 中刪除 Bestelling 參考并重新定義我們的@OneToMany關系

@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, , orphanRemoval = true)

@JoinColumn(name = "bestelling_id")

private List<Bestellingsregel> bestellingsregels = new ArrayList<>();


查看完整回答
反對 回復 2022-07-14
?
拉莫斯之舞

TA貢獻1820條經驗 獲得超10個贊

   Bestelling b = new Bestelling();

    Bestellingsregel br = new Bestellingsregel();

    br.setBestelling(b);

    List<Bestellingsregel> list = new ArrayList<>();

    list.add(br);

    b.setBestellingsregels(list);

    repo.save(b);

這對我有用。我猜你沒有在 Bestellingsregel 對象中設置 Bestelling 對象。


查看完整回答
反對 回復 2022-07-14
  • 2 回答
  • 0 關注
  • 93 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號