我想我误解了@多对一关系上下文中级联的含义。
案例:
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这一事实如何。所有影响我的数据(我猜是用户)?
请参阅这里的OpenJPA文档示例。CascadeType。ALL意味着它会做所有的动作。
引用:
CascadeType.PERSIST: When persisting an entity, also persist the entities held in its fields. We suggest a liberal application of this cascade rule, because if the EntityManager finds a field that references a new entity during the flush, and the field does not use CascadeType.PERSIST, it is an error.
CascadeType.REMOVE: When deleting an entity, it also deletes the entities held in this field.
CascadeType.REFRESH: When refreshing an entity, also refresh the entities held in this field.
CascadeType.MERGE: When merging entity state, also merge the entities held in this field.
塞巴斯蒂安。
CascadeType的含义。ALL是指持久化将传播(级联)所有EntityManager操作(PERSIST, REMOVE, REFRESH, MERGE, DETACH)到相关实体。
在您的情况下,这似乎是一个坏主意,因为删除一个地址将导致删除相关的用户。由于一个用户可以有多个地址,其他地址将成为孤儿。然而,相反的情况(注释User)是有意义的-如果一个地址只属于一个用户,如果该用户被删除,传播属于该用户的所有地址的删除是安全的。
顺便说一句:你可能想要给你的User添加一个mappedBy="addressOwner"属性来向持久化提供程序发出信号,表明连接列应该在ADDRESS表中。