当实体引用自身时,使用级联类型的正确方法是什么?

What is the correct way to use cascade type when an entities refers to itself?

提问人:rost shan 提问时间:8/2/2023 更新时间:8/2/2023 访问量:26

问:

假设我有以下实体(是 lombok):

@Data
@NoArgsConstructor
@AllArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
@Table(name = "entry")
@Entity
public class EntryEntity {
    @Id
    int id;

    String name;

    @EqualsAndHashCode.Exclude
    @ToString.Exclude
    @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.MERGE, CascadeType.PERSIST})
    @JoinColumn(name = "parent_id")
    EntryEntity entity;
}

该实体表示某个链接树,子条目引用其父项。我假设 1 个子有 1 个父实体。例如,我想在不同的事务中保存 2 个条目:

  1. EntryEntity child1 = new EntryEntity(2, "child1", new EntryEntity(1, "parent", null));
  2. EntryEntity child2 = new EntryEntity(3, "child2", new EntryEntity(1, "parent", null));.

child1并参考一个条目。child2parent

我使用带有 jakarta 注释的 H2 数据库和 Hibernate 实现。

当我尝试在不同的事务中保存 2 个孩子时,我收到错误:.休眠尝试保存两次条目。Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.ENTRY(ID) ( /* key:1 */ 1, 'root', NULL)"parent

我应该拒绝以这种方式使用级联保存,还是需要以某种方式配置休眠以解决我的问题?

Java Hibernate JPA H2 多对一

评论

1赞 Chris 8/3/2023
您不希望父级保留。您的问题是,当您持久化子实体时,您的级联设置告诉 JPA 也持久化父级 - 规范要求在持久化现有实体时抛出异常。因此,如果所有子项都仅与现有父项相关联,并且您不想执行在父项中读取的工作,并让它使用托管父项引用,则不要使用级联持久性。

答: 暂无答案