Hibernate不想为子实体保存ID。我有以下表格:
@Entity
@Table(name = "ct_orders")
data class Order(
@Id
@Column(name = "id")
@GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY)
val id: Int = 0,
@OneToMany(fetch = FetchType.LAZY, cascade = arrayOf(CascadeType.ALL), mappedBy = "order")
val route: List<Route>? = null,
...
)
@Entity
@Table(name = "ct_routes")
@JsonIgnoreProperties("id", "order")
data class Route(
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Int = 0,
@Column
val location: Point = GeoHelpers.point(),
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "order_id")
val order: Order? = null,
@Column
val title: String = ""
)
ct_routes在order_id中使用null保存。关系有问题吗?或者,我的代码可能有问题吗?
以下是代码的一部分,它保存了一个Order实体:
val order = orderRepository.save(Order(
...
route = GeoHelpers.placesListToEntities(data.places),
...
))
fun placesListToEntities(points: List<PlaceDto>) = points.map {
Route(
location = Helpers.geometry(it.location.latitude, it.location.longitude),
title = it.title
)
}
答案 0 :(得分:3)
您正在对bidirectional @OneToMany
进行建模,并且如文档中的示例所示,您负责在子项上设置父值>实体:
val order = orderRepository.save(Order(...).apply{
...
route = GeoHelpers.placesListToEntities(this, data.places),
...
})
fun placesListToEntities(order:Order, points: List<PlaceDto>) = points.map {
Route(
order = order,
location = Helpers.geometry(it.location.latitude, it.location.longitude),
title = it.title
)
}
PS。由于Route
是一个entity,您可以稍微更改一下模型以强制执行langauge级别的约束,即:
class Route internal constructor() {
lateinit var order: Order
constructor(order: Order) : this() {
this.order = order
}
}
有关详细信息,请参阅this question。