【发布时间】:2013-12-22 03:07:57
【问题描述】:
我正在尝试使用有序的孩子来建模双向父子设计。
当从父级删除子级(例如,3 个子级中的第 2 个子级)时,hibernate 生成的 sql 导致违反唯一约束,因为“更新”(兄弟)在“删除”(目标)之前执行。
我使用的 RDBMS (H2) 不支持延迟约束。除了以下选项,我还有哪些选择?
- 从架构中移除唯一约束
- 自己明确管理排序,而不是依赖休眠
有什么方法可以让休眠生成 sql 之前 'delete' 'update' ?
论坛中发现的一些旧讨论:
DELETE then INSERT in collection - Order of executed SQL
数据库架构:
CREATE TABLE IF NOT EXISTS Sequences (
ID BIGINT NOT NULL AUTO_INCREMENT,
Name LONGVARCHAR,
Type LONGVARCHAR,
Sequence LONGVARCHAR,
ParentId BIGINT DEFAULT NULL,
Index INT,
CONSTRAINT pk_SequenceId PRIMARY KEY (ID),
CONSTRAINT uc_Sequences UNIQUE (ParentId, Index),
CONSTRAINT fk_Sequences
FOREIGN KEY (ParentId)
REFERENCES Sequences(ID)
ON UPDATE CASCADE
ON DELETE CASCADE
);
类:
public class Sequence {
protected Long ID;
protected String name;
protected String type;
protected String sequence;
protected Sequence parentSequence;
protected List<Sequence> childSequences = new ArrayList<Sequence>();
}
HBM 映射:
<hibernate-mapping>
<class name="Sequence" table="Sequences">
<id name="ID" column="ID" type="long">
<generator class="native"/>
</id>
<property name="name" type="string" column="Name"/>
<property name="type" type="string" column="Type"/>
<property name="sequence" type="string" column="Sequence"/>
<many-to-one name="parentSequence" column="parentId" cascade="save-update" insert="false" update="false" class="Sequence" />
<list name="childSequences" inverse="false" lazy="true" cascade="all-delete-orphan">
<key column="parentId" not-null="true"/>
<list-index column="Index" base="0"/>
<one-to-many class="Sequence"/>
</list>
</class>
【问题讨论】:
标签: java sql hibernate unique-constraint self-referencing-table