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();
You have a bi-directional relationship, that is why you have to add the PhoneNumber
s in your Person
too. And use the mappedBy
attribute to show that the Person
is the inverse side and whenever it is deleted, please delete every phone number also.
Like this:
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
@OneToMany(mappedBy="person", cascade = CascadeType.ALL)
private Set<PhoneNumber> phoneNumbers;
}
Check this for more information.