Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA/Hibernate: on delete set null

So I've already noticed there is no easy solution to use on delete set null with JPA, but I heard there may be workarounds. My problem is the next (it's getting a bit abstract here, but I hope it still makes sense):

Imagine there are employees. Every employee knows their boss, but not the other way around. Bosses are employees themselves.

What I'm trying to accomplish:

If a boss gets fired, everybody who worked under him will lose his boss (obviously).

@Entity
@Table(name = "employee")
public class Employee
{
 @Column (name = "id" )
 private String id;

 @OneToOne
 @JoinColumn( name = "boss" )
 private employee boss;
}

This is how it worked in SQL:

ALTER TABLE EMPLOYEE
ADD CONSTRAINT CONSTRAINTNAME FOREIGN KEY (BOSS)
REFERENCES EMPLOYEE (ID)
ON DELETE SET NULL;

I don't want people without a boss to get fired as well, I just want them to lose their reference to their former boss. I saw solutions using @PreRemove but I am unsure if this does the same as I intend to.

thanks in advance!

like image 620
roqstr Avatar asked Sep 30 '22 08:09

roqstr


1 Answers

Yes @PreRemove() is a good way to go. But you need to have the bidirectional association on the inverse side, meaning Employee should have a @OneToMany with Employee (employees under supervision). And then add this method in Employee:

@PreRemove
private void removeAssociationsWithChilds() {
   for (Employee e : employees) {
        e.setBoss(null);
   }
}

But, if you don't want to keep track on the inverse side, meaning if you don't want to have a list of employees under supervision by the boss using @OneToMany, then you will have to do it manually via HQL just before deletion, such as update Employee e set e.boss = null where e.boss = ?, and then delete the boss.

like image 54
isah Avatar answered Oct 02 '22 15:10

isah