问题描述
我想我误解了在@ManyToOne
关系中级联的含义.
情况:
public class User {
@OneToMany(fetch = FetchType.EAGER)
protected Set<Address> userAddresses;
}
public class Address {
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
protected User addressOwner;
}
cascade = CascadeType.ALL
的含义是什么?例如,如果我从数据库中删除某个地址,那么添加cascade = CascadeType.ALL
的事实如何影响我的数据(我猜是User
)?
CascadeType.ALL
的含义是,持久性会将所有EntityManager
操作(PERSIST, REMOVE, REFRESH, MERGE, DETACH
)传播(层叠)到相关实体.在您看来,这是个坏主意,因为删除Address
会导致删除相关的User
.由于用户可以有多个地址,因此其他地址将成为孤立地址.但是,相反的情况(用User
注释)是有道理的-如果一个地址仅属于一个用户,则删除该用户可以安全地传播对属于该用户的所有地址的删除.
顺便说一句:您可能想在User
中添加mappedBy="addressOwner"
属性,以向持久性提供程序发出信号,告知联接列应位于ADDRESS表中.
I think I misunderstood the meaning of cascading in the context of a @ManyToOne
relationship.
The case:
public class User {
@OneToMany(fetch = FetchType.EAGER)
protected Set<Address> userAddresses;
}
public class Address {
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
protected User addressOwner;
}
What is the meaning of the cascade = CascadeType.ALL
? For example, if I delete a certain address from the database, how does the fact that I added the cascade = CascadeType.ALL
affect my data (the User
, I guess)?
The meaning of CascadeType.ALL
is that the persistence will propagate (cascade) all EntityManager
operations (PERSIST, REMOVE, REFRESH, MERGE, DETACH
) to the relating entities.
It seems in your case to be a bad idea, as removing an Address
would lead to removing the related User
. As a user can have multiple addresses, the other addresses would become orphans. However the inverse case (annotating the User
) would make sense - if an address belongs to a single user only, it is safe to propagate the removal of all addresses belonging to a user if this user is deleted.
BTW: you may want to add a mappedBy="addressOwner"
attribute to your User
to signal to the persistence provider that the join column should be in the ADDRESS table.
这篇关于@ManyToOne JPA关联的CascadeType.ALL是什么意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!