删除实体会自动更新它们的关系吗?
假设 Person
实体有一个 List
listOfAddresses
字段,它是与 Address
实体的 @ManyToMany
或 @OneToMany
关系。如果我使用 em.remove("James's_address")
删除 Address
,listOfAddresses
是否会自动更新以删除 ”詹姆斯的地址”
?Suppose the Person
entity has a List<Address> listOfAddresses
field which is either @ManyToMany
or @OneToMany
relationship with the Address
entity. If I remove an Address
with em.remove("James's_address")
, will the listOfAddresses
automatically get updated to remove "James's_address"
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这取决于。
如果您有 OneToMany,并且地址表具有该人员的外键,则删除该地址将起作用。如果在删除地址之前已将人员及其地址加载到会话中,则其地址列表仍将包含已删除的地址。您必须自己维护所有关联。如果该人的地址尚未加载,则加载时,列表显然不会包含已删除的地址,因为 Hibernate 不会在数据库中找到它。
如果 OneToMany 使用联接表,或者如果它是 ManyToMany,则删除该地址而不将其从引用该地址的所有人员的地址列表中删除将导致异常,因为联接表将继续引用您指定的地址。想要删除。外键约束是导致异常的原因。
It depends.
If you have a OneToMany, and the address table has a foreign key to the person, removing the address will work. If the person and its addresses have been loaded in the session prior to the deletion of the address, its list of addresses will still contain the deleted address. You have to maintain all the associations yourself. If the person's addresses have not been loaded yet, when they are loaded, the list won't contain the deleted address, obviously, since Hibernate won't find it in the database.
If the OneToMany uses a join table, or if it's a ManyToMany, then deleting the address without removing it from te list of addresses of all the persons referencing it will lead to an exception, since the join table will continue to reference an address that you want to delete. The foreign key constraint is what will cause the exception.