【发布时间】:2018-11-06 02:20:36
【问题描述】:
我使用 Spring Boot 和 JPA 开发 API
我在双向 OneToMany 关系中发现了一个案例,当 JSON 有效负载这样请求时,我的父 ID 没有保存在数据库中:
{
"name": "Rice",
"description": "Lorem ipsum dolor sit amet",
"variants": [
{
"amount": 1,
"unit": "kg",
"price": 60000
}
]
}
这是我的模型:
Product.kt
data class Product(
@Id
@GeneratedValue
var id: Long = 0,
var name: String = "",
var photo: String = "",
var description: String = "",
@OneToMany(mappedBy = "product", cascade = [CascadeType.ALL])
@JsonBackReference
var variants: MutableList<Variant> = mutableListOf()
)
Variant.kt
@Entity
data class Variant(
@Id
@GeneratedValue
var id: Long = 0,
var amount: Int = 0,
var unit: String = "",
var price: Double = 0.0,
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "product_id")
@JsonManagedReference
var product: Product? = null
)
是否需要应用其他配置? 谢谢
【问题讨论】:
-
你可以尝试设置@JoinColumn(name = "product_id", nullable = false) 看看会发生什么?
-
@SimonMartinelli 我收到此错误
Column 'product_id' cannot be null并抛出此异常could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
标签: spring-boot jpa kotlin relationship one-to-many