持久性异常外键约束在休眠中失败
我在 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;
}
当我保留电话号码对象或人员对象时,它会被正确插入。 但当我这样做时
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您具有双向关系,这就是为什么您也必须在
Person
中添加PhoneNumber
。并使用mappedBy
属性来表明Person
是反面,每当删除它时,请同时删除所有电话号码。像这样:
查看此了解更多信息。
You have a bi-directional relationship, that is why you have to add the
PhoneNumber
s in yourPerson
too. And use themappedBy
attribute to show that thePerson
is the inverse side and whenever it is deleted, please delete every phone number also.Like this:
Check this for more information.
首先,您必须在两个类中定义 Person 和 PhoneNumber 之间的关系。
抛出错误是因为电话号码取决于您删除的人员对象。
如果添加@OneToMany,您还可以定义属性cascade = CascadeType.ALL,然后所有电话号码都会被删除。
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 propertycascade = CascadeType.ALL
and then all phone numbers are removed consequently.