首页 > 解决方案 > Hibernate 没有插入外键 ManyToOne 实体

问题描述

我想知道为什么 Hibernate 没有将外键插入数据库。

我在 2 个类之间有 OneToMany 和 ManyToOne 关系。

@Entity
@Data
public 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
@Data
public 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> {
}

标签: javamysqlhibernatejpa

解决方案


您在 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<>();
    

推荐阅读