java - Hibernate级联删除依赖实体(ManyToOne OneToMany)
问题描述
在项目中有实体帐户和服务(摘要)。服务有一个子类,存款。账户类代码:
@Entity
public class Account {
private static Logger log = LogManager.getLogger(Account.class);
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column
private double amount;
@Column
private AccountType type;
@Column(name = "date_start")
private Date dateStart;
@Column(name = "date_end")
private Date dateEnd;
@Column(name = "in_rate")
private short inRate;
@ManyToOne
@JoinColumn(name = "client_id")
private Client client;
...
服务类代码:
@MappedSuperclass
abstract public class Services {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected long id;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "from_acc_id")
protected Account fromAcc;
...
存款还有一个金额字段,但这不是那么重要:
@Entity
public class Deposit extends Services {
@Column
private double amount;
当试图删除一个 Account 实例时,它有来自 Deposit 的链接,它给出了一个错误:
2020-03-13 13:29:51 ERROR SqlExceptionHelper: 131 - ERROR: UPDATE or DELETE in the "account" table violates the foreign key constraint "fk8qcea1frw0og19kft1ltq9kf9" of the "deposit" table
Details: The key (id) = (1) still has links in the "deposit" table.
如何配置级联删除,以便在删除账户记录时,自动删除存款记录?
解决方案
通常,注释 @OnDelete 有所帮助。Account 类没有改变。服务代码:
@MappedSuperclass
abstract public class Services {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected long id;
@ManyToOne(cascade = CascadeType.REFRESH)
@JoinColumn(name = "from_account_id")
@OnDelete(action = OnDeleteAction.CASCADE)
protected Account fromAcc;
...
推荐阅读
- javascript - Recharts 垂直渲染饼图
- c++ - 如何使用c ++获取在给定目录中创建的最新文件夹的名称
- java - 简单的 Spring Boot 微服务 - 内存使用消耗超过 300 MB
- javascript - 修复显示中的背景线性颜色:flex 溢出滚动内容 - CSS
- ruby-on-rails - Stripe SCA 一次性付款 Rails
- javascript - 如何在 Reactjs 中的功能组件之间传递值?
- r - 使用具有不均匀输出 R 的 df 列创建日期范围向量
- python - 如何避免超出“while”中的时间限制?(Python)
- mysql - 如何在不显示垃圾字符的情况下导入 csv 文件?
- electron - 离子 5 + 电子