【问题标题】:Hibernate saves child entity with null parent idHibernate 使用 null 父 id 保存子实体
【发布时间】:2016-09-17 01:48:01
【问题描述】:

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
    )
}

【问题讨论】:

  • 你是在保存之前设置Route对象的order属性吗?

标签: spring hibernate jpa kotlin


【解决方案1】:

您正在为 bidirectional @OneToMany 建模,如文档中的示例所示,您负责在 child 实体上设置 parent 值:

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

【讨论】:

    猜你喜欢
    • 2021-07-09
    • 2012-11-10
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多