Reputation: 15
I have a @ManyToOne Uni-directional relationship between person and car, meaning a car can be owned by several persons. The problem is when I delete a car, the car id's is not deleted from the Person's entity join-column. Is there a way to configure JPA to remove car id's from the owner person join-column after deleting a car?
Note: Using orpahRemoval=true will not help, since I need to update the parent's car reference to null, and each entity (Car / Person) is not dependent on the existence of the other...
@Entity
public class Car{
@Id
@GeneratedValue
private long id;
}
@Entity
public class Person {
@Id
@GeneratedValue
private long id;
@ManyToOne
@JoinColumn(name="CAR_ID")
private Car car;
}
Upvotes: 1
Views: 642
Reputation: 692073
No. You'll need to execute a query to find all the persons with the given car, set their car to null, then delete the car:
List<Person> persons = em.createQuery("select p from Person p where p.car = :car", Person.class)
.setParameter("car", car)
.getResultList();
for (Person person : persons) {
person.setCar(null);
}
em.remove(car);
Upvotes: 1