java - 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> {
}
解决方案
您在 Bestellingsregel 将 Bestelling 和 Bestellingsregel 之间的关系定义为与拥有方(持有外键)的双向关系,这是正确的,但有利也有弊。
您有以下选择:
- 使用定义的关系并将 Bestelling 对象设置为列表中的每个 Bestellingsregel 对象。Bestellingsregel 是拥有方,因此您必须在保存前直接设置参考。
使您的关系单向:从 Bestellingsregel 中删除 Bestelling 参考并重新定义我们的
@OneToMany
关系@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, , orphanRemoval = true) @JoinColumn(name = "bestelling_id") private List<Bestellingsregel> bestellingsregels = new ArrayList<>();
推荐阅读
- apache-spark - How do i pass Env variales to a spark job?
- c# - Unable to read file in Hololens
- c# - Azure 函数在 Linux 上出现“无法启动的侦听器”错误
- kubernetes - How to list microk8s' containers with microk8s.ctr
- python - 如何用函数计算python中的唯一单词?
- c# - DatePicker 中日期的垂直对齐方式
- machine-learning - 如何限制 LSTM 模型中的序列预测以匹配特定模式?
- php - How to use ajax for saving image with php
- xpath - 如何更新具有最大子属性的 XML 属性节点?
- visual-studio-code - Keyboard shortcut to switch from source control "diff" mode back into normal editing?