2

I have following entity model.

@Entity
@Table(name="product")
public class ProductEntity {
      @Id
      @GeneratedValue(generator = "uuid2")
      @GenericGenerator(name = "uuid2", strategy = "uuid2")
      private UUID id;

      ...


      @OneToMany(mappedBy = "productEntity", cascade = CascadeType.ALL)
      private List<ProductAddonEntity> productAddonEntities;
 }


@Entity
@Table(name="product_addon")
public class ProductAddonEntity {
      @Id
      @GeneratedValue(generator = "uuid2")
      @GenericGenerator(name = "uuid2", strategy = "uuid2")
      private UUID id;

      ...


      @ManyToOne()
      @JoinColumn(name = "addon_id")
      private ProductEntity addonEntity;
 }

I want to delete product, and that deletion should also delete all ProductAddon entities, connected with this product. So I declare one to many relation with all cascade types. But when I try to delete some product, at the beginning Hibernate tries to set null addon_id in product_addon table. But this column have non-null constraint, so deletion fails.

So I added to annotation @ManyToOne parameters

    @JoinColumn(name = "addon_id", nullable = false, updatable = false)

But now hibernate just tries to delete product, before deleting product_addon entities, connected with this product. And this deletion fails because of foreign key constraint (Cannot delete or update a parent row: a foreign key constraint fails).

What can be a problem here? This application also uses liquibase, so foreign keys generated not by hibernate. For example, foreign key for addon_id doesn't have actions on delete, but I'm thinking that hibernate does not need these actions, because it works on higher data layer

Dima Stoyanov
  • 121
  • 1
  • 11

1 Answers1

0

Orphan removal is aggressive remove cascading mode to remove child object whenever the parent object needs to be deleted(@OneToOne and @OneToMany relationships). This feature added from JPA 2.0 version.JPA deletion operation

The difference between the two settings is in the response to disconnecting a relationship. For example, such as when setting the address field to null or to another Address object.

@Entity   
class Employee {

@OneToOne(cascade=CascadeType.REMOVE)
private Address address;

}

If only cascade=CascadeType.REMOVE is specified no automatic action is taken since disconnecting a relationship is not a remove operation.

@Entity
class Employee {

@OneToOne(orphanRemoval=true)
private Address address;

}

If orphanRemoval=true is specified the disconnected Address instance is automatically removed. This is useful for cleaning up dependent objects (e.g. Address) that should not exist without a reference from an owner object (e.g. Employee).

Roshini
  • 85
  • 1
  • 8