Anil G
Anil G

Reputation: 187

How to delete only a parent entity in JPA

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

Answers (3)

Anil G
Anil G

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

Predrag Maric
Predrag Maric

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

V G
V G

Reputation: 19002

  1. I doubt the relationship is @OneToOne, as there are many employees that have the same manager.
  2. 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

Related Questions