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

36 Views Asked by At

Assume that I have the following entity (Yes with 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;
}

That entity represents some linked tree, that children entries refer to their parents. I assume that 1 child has 1 parent entity. For example, I want to save 2 entries in different transaction:

  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 and child2 refer to the one entry parent.

I use H2 database with jakarta annotations with Hibernate Implementation.

When I try to save 2 children in different transactions, I receive the error: Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.ENTRY(ID) ( /* key:1 */ 1, 'root', NULL)". Hibernate try to save twice parent entry.

Should I refuse to use cascade saving in that way or do I need to configure hibernate somehow in order to fix my problem?

0

There are 0 best solutions below