gpt4 book ai didi

spring - Hibernate保存具有空父ID的子实体

转载 作者:行者123 更新时间:2023-12-02 12:43:59 26 4
gpt4 key购买 nike

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中保存为空。关系有问题吗?还是我的代码可能有问题?

这是代码的一部分,用于保存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
)
}

最佳答案

您正在建模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。由于 Routeentity,因此您可以稍微更改模型以在语言级别上施加约束,即:
class Route internal constructor() {
lateinit var order: Order

constructor(order: Order) : this() {
this.order = order
}
}

有关更多详细信息,请参见 this question

关于spring - Hibernate保存具有空父ID的子实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37335779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com