【发布时间】:2020-11-09 17:41:42
【问题描述】:
我在更新我的实体时遇到问题。如您所见,我有三个实体。
LabelValueEntity 拥有来自 LabelSwitchEntity 类的列表。LabelSwitchEntity 拥有来自 SwitchCaseEntity 类的列表。
从我的 SQL 语句中可以看出,name 和 labelValueUUID 字段是唯一的。我的表格中只允许该组合的一行。
当我使用 LabelSwitchEntity 类的新列表更新父实体 (LabelValueEntity) 时,我希望 Hibernate 删除旧列表本身并创建新实体。一个一个地更新孩子有点困难。这就是为什么我想直接删除所有相关的孩子。
当我更新 LabelValueEntity 并为其提供包含具有唯一名称的 LabelSwitchEntity 和 labelValueUUID(数据库中已经存在的实体)组合的列表时,我得到一个唯一约束违规异常。好吧,这个错误很明显,因为正如我所说,该组合存在于数据库中。我希望 Hibernate 足够聪明,可以在插入子之前删除它。
我做错了什么?
@Entity
@Table(name = "label_value")
class LabelValueEntity(uuid: UUID? = null,
...
@OneToMany(
mappedBy = "labelValueUUID",
cascade = [CascadeType.ALL],
fetch = FetchType.EAGER,
orphanRemoval = true)
@Fetch(FetchMode.SUBSELECT)
val labelSwitchEntities: List<LabelSwitchEntity>? = emptyList()
) : BaseEntity(uuid)
@Entity
@Table(name = "label_switch")
class LabelSwitchEntity(uuid: UUID? = null,
@Column(name = "label_value_uuid", nullable = false)
val labelValueUUID: UUID,
@OneToMany(
mappedBy = "labelSwitchUUID",
cascade = [CascadeType.ALL],
fetch = FetchType.EAGER,
orphanRemoval = true
)
val switchCaseEntities: List<SwitchCaseEntity>,
@Column
val name: String,
...
) : BaseEntity(uuid)
@Entity
@Table(name = "switch_case")
class SwitchCaseEntity(uuid: UUID? = null,
...
@Column(name = "label_switch_uuid", nullable = false)
val labelSwitchUUID: UUID
) : BaseEntity(uuid)
CREATE TABLE label_switch
(
uuid UUID NOT NULL PRIMARY KEY,
label_value_uuid UUID REFERENCES label_value(uuid) ON DELETE CASCADE,
name CHARACTER VARYING (255) NOT NULL,
UNIQUE (label_value_uuid, name)
);
CREATE TABLE switch_case
(
uuid UUID NOT NULL PRIMARY KEY,
label_switch_uuid UUID NOT NULL REFERENCES label_switch(uuid) ON DELETE CASCADE
);
基础实体
@MappedSuperclass
abstract class BaseEntity(givenId: UUID? = null) : Persistable<UUID> {
@Id
@Column(name = "uuid", length = 16, unique = true, nullable = false)
private val uuid: UUID = givenId ?: UUID.randomUUID()
@Transient
private var persisted: Boolean = givenId != null
override fun getId(): UUID = uuid
@JsonIgnore
override fun isNew(): Boolean = !persisted
override fun hashCode(): Int = uuid.hashCode()
override fun equals(other: Any?): Boolean {
return when {
this === other -> true
other == null -> false
other !is BaseEntity -> false
else -> getId() == other.getId()
}
}
@PostPersist
@PostLoad
private fun setPersisted() {
persisted = true
}
}
【问题讨论】:
-
this 不是完全相同的问题吗?
-
为了完整性:你的
BaseEntity是什么? -
@MichaelPiefel 为了完整性,我添加了 BaseEntity
标签: java spring kotlin jpa spring-data-jpa