JPA / Hibernate: when removing set null
So, I already noticed that there is no easy solution to use on delete set null
with JPA, but I heard that there might be workarounds. My problem is as follows (it gets a little abstract here, but I hope it still makes sense):
Imagine the staff . Every employee knows their boss , but not vice versa. Bosses are the employees themselves.
What I am trying to accomplish:
If the boss gets fired, everyone who worked under him will lose their 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 works 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 quit too, I just want them to lose their link to their former boss. I've seen solutions using @PreRemove, but I'm not sure if it does the same thing I do.
early!
source to share
Yes @PreRemove()
- a good way. But you need to have bi-directional communication on the back, that is, you Employee
must have @OneToMany
with Employee
(supervised employees). Then add this method to Employee
:
@PreRemove
private void removeAssociationsWithChilds() {
for (Employee e : employees) {
e.setBoss(null);
}
}
But if you do not want to track the downside, that is, if you do not want to have a list of employees under the supervision of the boss using @OneToMany
, then you will have to do it manually via HQL before deleting, for example update Employee e set e.boss = null where e.boss = ?
, and then deleting the boss.
source to share