Home > Back-end >  Implement "reverse" orphan removal with JPA
Implement "reverse" orphan removal with JPA

Time:09-28

I have an entity Address that is referenced by several other entities, for example:

@Entity
class Office {
    @OneToOne
    private Address address;

    ...
}

@Entity
class Home {
    @OneToOne
    private Address address;

    ...
}

where

@Entity
class Address {
    @Id
    private Long id;
    private String street;
    private String zipCode;
    
    ...
}

The field referencing Address in the other entities is nullable, so I'd like that when, for example, Office.address is set to null, the referenced entity is removed from database.

This is similar to how orphanRemoval works, but in my situation I need that the parent class (Address) instance is removed, instead of the child.

Is there a way to achieve this using a declarative way, or shoul I manually remove the unreferenced Addresses?

NOTES

  • a new address is created every time a new Office/Home/etc. is created. (There are no shared addresses referenced by other entities.)

  • I tried to apply orphanRemoval to @OneToOne annotation, but setting the address field to null doesn't trigger the (Address) entity to be removed from the database.

  • I already checked this answer: https://stackoverflow.com/a/31471415/1061499, but this is not applicable to my case. I can't include a cross reference in my Address class.

CodePudding user response:

Replicating your problem as follows, orphanRemoval works as expected: https://github.com/fladdimir/so-jpa/blob/b324b3d2867ba62ee3e96357822ea9aee86a10a0/src/test/java/org/demo/address/AddressTest.java#L57

@Entity
@Data
class Home {

  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE)
  private Long id;

  @OneToOne(orphanRemoval = true) // should work as shown in the linked test
  private Address address; // <- associated entity is removed when set to 'null'
}

Does this work for you? If not, what are the differences to your setup?

  • Related