带有CascadeType.ALL的JPA @ManyToOne [英] JPA @ManyToOne with CascadeType.ALL

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

问题描述

我想我在 @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 的事实如何影响我的数据(用户,我想)?

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.

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

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:您可能想要在中添加 mappedBy =addressOwner属性用户向持久性提供程序发出连接列应该在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.

这篇关于带有CascadeType.ALL的JPA @ManyToOne的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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