@ManyToOne JPA 关联的 CascadeType.ALL 的含义是什么 [英] What is the meaning of the CascadeType.ALL for a @ManyToOne JPA association

查看:23
本文介绍了@ManyToOne JPA 关联的 CascadeType.ALL 的含义是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我误解了 @ManyToOne 关系上下文中级联的含义.

I think I misunderstood the meaning of cascading in the context of a @ManyToOne relationship.

案例:

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,我猜)?

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)?

推荐答案

CascadeType.ALL 的含义是持久化将传播(级联)所有 EntityManager 操作(PERSIST, REMOVE, REFRESH, MERGE, DETACH) 到相关实体.

The meaning of CascadeType.ALL is that the persistence will propagate (cascade) all EntityManager operations (PERSIST, REMOVE, REFRESH, MERGE, DETACH) to the relating entities.

在您的情况下,这似乎是一个坏主意,因为删除 Address 会导致删除相关的 User.由于一个用户可以有多个地址,其他地址将成为孤儿.然而,相反的情况(注释 User)是有意义的 - 如果一个地址只属于一个用户,如果该用户被删除,传播属于该用户的所有地址的删除是安全的.

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.

顺便说一句:您可能希望将 mappedBy="addressOwner" 属性添加到您的 User 以通知持久性提供者连接列应该在 ADDRESS 表中.

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 的含义是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆