'Persistence Exception foreign key contraint fails in hibernate
I have defined the following two classes in hibernate
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
}
@Entity
public class PhoneNumber {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToOne(cascade = CascadeType.ALL)
private Person person;
}
When I persist a phone number object or a person object it's getting inserted properly.
But when I do
Person person = session.get(Person.class,1);
session.remove(person);
transaction.commit();
I get the foreign key violation exception. But since I have declared a column as ManyToOne shouldn't hibernate automatically delete the corresponding phonnumber records?
I am not sure if I need to add any extra code to do that
Solution 1:[1]
First of all, you have to define the relationship between Person and PhoneNumber in both classes.
The error is thrown because there are phone numbers depending on the person object you removed.
If you add @OneToMany you can define also the property cascade = CascadeType.ALL and then all phone numbers are removed consequently.
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
@OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
private List<PhoneNumber> phoneNumbers;
}
@Entity
public class PhoneNumber {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToOne
private Person person;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | frascu |
