Reputation: 187
I have a Person object. Person has a manager property which is again of type Person.
@OneToOne(optional = true, cascade = { CascadeType.ALL })
private Person manager;
Say John is the manager and Bob is the employee. When I am trying to delete John, it fails since Bob becomes orphan (without Manager). That should be allowed in my use case. But marking this relationship "optional" doesn't help. And Cascade doesn't seem to have any significance here.
I presume this is possible with JPA. Any help?
@Entity
public class Person {
@Id
private String id;
private String name;
private Integer age;
private Address address;
@JoinColumn(name = "manager_id", nullable = true, insertable = true, updatable = true)
@OneToOne(optional = true, cascade = { CascadeType.ALL })
private Person manager;
@OneToMany(mappedBy = "manager", cascade = { CascadeType.ALL })
public Collection<Person> reportees;
Upvotes: 0
Views: 550
Reputation: 187
I deleted the parent entity before deleting children. Not the ideal solution but works for me.
I also tried the bidirectional relationship (by adding @ManyToOne reportees property of type Person) and marked the relationship "optional" using @JoinColumn also marked nullable=true. But nothing worked.
Upvotes: 0
Reputation: 24403
You should set null
as Bob's manager, before trying to delete John. Also, @Andrei is right, you should map this as bidirectional @ManyToOne
relation (although your code will work if you know all the persons that have John as their manager).
Upvotes: 1
Reputation: 19002
@OneToOne
, as there are many employees that have the same manager.If you insist that it is @OneToOne
, then make the relationship bidirectional, by adding the property in the Person
Java class:
@OneToOne(mappedBy="manager", cascade = { CascadeType.ALL })
private Person employee;
Upvotes: 0